Python 3.7如何通过插座模块连接两台PC

时间:2018-10-24 00:39:30

标签: python-3.x

我正在尝试用python连接两台计算机并在它们之间传输数据。我搜索了Google并获得了这样的代码。

# Save as client.py 
# Message Sender
import os
from socket import *
host = "192.168.0.11" # set to IP address of target computer
port = 13000
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
while True:
    data = input("Enter message to send or type 'exit': ")
    UDPSock.sendto(data.encode('utf-8'), addr)
    if data == "exit":
        break
UDPSock.close()
os._exit(0)

# Save as server.py 
# Message Receiver
import os
from socket import *
host = "" # I'm not sure what to put here
port = 13000
buf = 1024
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(addr)
print ("Waiting to receive messages...")
while True:
    (data, addr) = UDPSock.recvfrom(buf)
    print ("Received message: " + data)
    if data == "exit":
        break
UDPSock.close()
os._exit(0)

当我尝试发送消息时,我发现消息已发送,但另一台计算机未收到任何信息……我该怎么办?

1 个答案:

答案 0 :(得分:1)

除了在客户端data = data.decode()之后需要recvfrom之外,该代码也可以工作。我在客户端上使用host = 'localhost'测试了您的代码,并在同一台计算机上同时运行了客户端和服务器,并且可以正常工作。您可能需要调整防火墙,以允许一台或两台计算机上的端口13000上的UDP通信。