如何从 UDP 服务器发送 UDP 消息而不发送给自己?

How to send UDP message from UDP server without sending to itself?

我想制作一个 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 编程经验。如果您发现任何问题,请告诉我。

此代码的问题是服务器回复了自己,而不是远程客户端。在这里:

data, address = self.sock.recvfrom(8192)
# ...
bytes_sent = self.sock.sendto(msg_server.SerializeToString(), self.remote)

应该是:

bytes_sent = self.sock.sendto(msg_server.SerializeToString(), address)

remote 重命名为 server_address 很有意义,因为它是此服务器的地址。