我想做一个UDP服务器,在服务器从客户端收到消息后立即向UDP客户端发送消息。我使用Python和googleprotobuffer作为消息协议。在
目前,消息接收部分似乎可以工作,但是对于消息发送部分,它有一个问题:来自服务器的响应消息没有到达客户端,更糟糕的是,服务器显示了该消息(可能是它自己发送的?现在,控制台显示来自客户端的消息和应该发送到客户端的消息)。当我尝试C++或C语言上的类似代码时,这个问题就没有发生。在
以下是我的代码摘录:def connect(self):
remote = ('x.x.x.x',xxxx) #ip and port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(2.5)
self.sock.bind(remote)
self.sock.settimeout(None)
def start(self):
while not self.exit_thread:
# Get the message from client
data, address = self.sock.recvfrom(8192)
if data is not None:
# De-serialize inbound message from client
msg_client = xxx_pb2.msgClient()
msg_client.ParseFromString(data)
# Display message from client
self.display_inbound_message(msg_client)
# Create a new message from server
msg_serer = xxx_pb2.msgServer()
self.create_outbound_message(msg_serer)
# Send the Udp message to the client, return the number of bytes sent
bytes_sent = self.sock.sendto(msg_server.SerializeToString(), self.remote)
if (bytes_sent < 0):
print("Error send message")
我没有足够的UDP编程经验。如果你注意到什么,请告诉我。在