【发布时间】:2017-02-08 08:31:57
【问题描述】:
我想创建一个 UDP 服务器,在服务器从客户端收到消息后立即向 UDP 客户端发送消息。我使用 Python 和 Google Protobuffer 作为消息协议。
目前,消息接收部分似乎工作,但关于消息发送部分,它有一个问题:来自服务器的响应消息没有到达客户端,更糟糕的是,服务器显示该消息(可能它发送到本身?现在,控制台显示来自客户端的消息和应该发送给客户端的消息)。当我在 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")
我没有足够的 Python UDP 编程经验。如果您发现任何问题,请告诉我。
【问题讨论】:
-
你怎么称呼这个函数?是否在
thread中? -
我暂时不使用
thread,但打算在弄清楚这个问题后使用它。和这个问题有关系吗?
标签: python sockets udp protocol-buffers