[英]How to send UDP message from UDP server without sending to itself?
I'd like to make a UDP server that sends a message to a UDP client soon after the server gets the message from the client. 我想制作一个UDP服务器,该服务器在从客户端获取消息后立即向UDP客户端发送消息。 I'm using Python and Google Protobuffer as a message protocol.
我正在使用Python和Google Protobuffer作为消息协议。
Currently, the message receiving part seems working, but regarding the message sending part, it has an issue: the response message from the server doesn't arrive the client and even worse, the server shows that message (maybe it sends to itself? Right now, the console shows both the message from client and the message that should be sent to client). 当前,消息接收部分似乎正常工作,但是对于消息发送部分,它有一个问题:来自服务器的响应消息没有到达客户端,甚至更糟的是,服务器显示了该消息(也许它发送给自己了吗?现在,控制台将同时显示来自客户端的消息和应发送给客户端的消息。 This issue didn't happen when I tried the similar code on C++ or C#.
当我在C ++或C#上尝试类似的代码时,没有发生此问题。
The followings are some excerpt from my code: 以下是我的代码的摘录:
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")
I don't have enough experience for UDP programming on Python. 我在Python上进行UDP编程的经验不足。 Please let me know if you notice anything.
如果您有任何注意事项,请告诉我。
The issue with this code is that the server replies to itself, rather than the remote client. 此代码的问题是服务器回复自身,而不是远程客户端。 In here:
在这里:
data, address = self.sock.recvfrom(8192)
# ...
bytes_sent = self.sock.sendto(msg_server.SerializeToString(), self.remote)
It should be: 它应该是:
bytes_sent = self.sock.sendto(msg_server.SerializeToString(), address)
It makes good sense to rename remote
to server_address
because it is this server's address. 将
remote
重命名为server_address
是很有意义的,因为它是该服务器的地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.