python 双机通信
时间: 2023-08-13 13:10:45 浏览: 143
利用socket实现双机通信
Python双机通信可以使用socket库来实现。在服务器端,可以使用TCP协议来实现局域网聊天。以下是一个示例代码:
```python
from socket import *
from threading import Thread
import time
IP = '0.0.0.0' # 全部开放
PORT = 50000
BUFLEN = 512
listenSocket = socket(AF_INET, SOCK_STREAM)
listenSocket.bind((IP, PORT))
listenSocket.listen(5)
print(f'success,waiting for {PORT}')
dataSocket, addr = listenSocket.accept()
print('connect one', addr)
class Get(Thread):
def run(self):
while True:
time.sleep(1)
recved = dataSocket.recv(BUFLEN)
if not recved:
break
info = recved.decode()
print(' << ' + info + '\n>>', end='')
class Send(Thread):
def run(self):
while True:
info = input('>>')
dataSocket.send(info.encode())
if __name__ == '__main__':
Send().start()
Get().start()
```
在客户端,可以使用相同的socket库来实现与服务器的通信。以下是一个示例代码:
```python
import os
import sys
import time
from socket import *
from threading import Thread
IP = '略' # 服务器ip
SERVER_PORT = 50000
BUFLEN = 512
print("he isn't here")
while True:
try:
time.sleep(5)
dataSocket = socket(AF_INET, SOCK_STREAM)
dataSocket.connect((IP, SERVER_PORT))
break
except:
pass
class Send(Thread):
def run(self):
while True:
toSend = input(">>")
if toSend == '':
break
dataSocket.send(toSend.encode())
class Get(Thread):
def run(self):
while True:
time.sleep(1)
recved = dataSocket.recv(BUFLEN)
if not recved:
break
print(' << ' + recved.decode() + '\n>>', end='')
if __name__ == '__main__':
os.system("cls")
print("you have connected him")
Send().start()
Get().start()
```
这样,服务器端和客户端就可以通过TCP协议进行双机通信了。\[1\]\[2\]
#### 引用[.reference_title]
- *1* *2* [用python实现两台主机通讯](https://blog.csdn.net/m0_62165273/article/details/122314778)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [一种双机跨网段实现通信的解决方法](https://blog.csdn.net/jhui123456/article/details/118392231)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文