我正在运行 UDP 服务器和客户端(python)。当在同一个本地网络中时,客户端能够与服务器通信。但是,当服务器 IP 地址设置为路由器的 IP 地址(具有向服务器转发的 UDP 端口)时,客户端根本无法与服务器通信。我想知道是否有人可以指出为什么这在本地网络中(在不同的机器上)有效,但我无法使用客户端和服务器都连接到的路由器的外部 IP 地址使客户端连接到服务器。
客户端的代码
import socket
import sys
HOST, PORT = "<IP address of router which is port forwarded to server>", 5000
data = " Hello from Client" #.join(sys.argv[1:])
# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(data + "\n", (HOST, PORT))
received = sock.recv(1024)
print "Sent: {}".format(data)
print "Received: {}".format(received)
服务器的代码
import SocketServer
class MyUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print "{} wrote:".format(self.client_address[0])
print data
socket.sendto(data.upper(), self.client_address)
if __name__ == "__main__":
HOST, PORT = "<local IP address of server", 5000
server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
server.serve_forever()