从外部IP将TCP客户端连接到我的服务器

问题描述 投票:0回答:1

我用Python制作了一个简单的TCP服务器和客户端。当我使用服务器的本地IP时,一切正常,但不能使用公共IP。我的服务器具有静态IP并且绑定到此IP和端口,并且客户端尝试使用相同的端口连接到公共IP。我已经在我的路由器上设置了端口转发,据称将流量重定向到该端口到服务器的本地IP。路由器是Netgear X4S R7800。

服务器和客户端都不会崩溃。客户端最终超时并抛出异常,服务器似乎根本没有收到任何连接。

server.朋友

from socket import *
SERVER_NAME = '192.168.1.140' #My server's (static) local IP
SERVER_PORT = 12100

def initializeServer():
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverSocket.bind((SERVER_NAME, SERVER_PORT))
    serverSocket.listen(5)
    print("Server initialized to port " + str(SERVER_PORT) +"...")
    return serverSocket

def serverLoop(serverSocket):
    while True:
        connectionSocket, addr = serverSocket.accept() #Gets stuck here
        print("Connected to", addr)
        listenToClient(connectionSocket)
        print("Terminating client connection ...")
        connectionSocket.close()

if __name__ == '__main__':
    serverSocket = initializeServer()
    try:
        serverLoop(serverSocket)
    except KeyboardInterrupt:
        shutdownServer(serverSocket)
        print("\nServer shut down")

client.朋友

import socket
SERVER_NAME = '193.91.XXX.XXX'  #Public IP
SERVER_PORT = 12100

def connectToServer(serverName, serverPort):
    clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    clientSocket.connect((serverName, serverPort)) #Gets stuck here and eventually times out
    return clientSocket

def main():
    try:
        serverSocket = connectToServer(SERVER_NAME, SERVER_PORT)
    except Exception as e:
        print("Cannot connect to the server\n", e)
    else:
        print("Connected to server")
        try:
            askForUserAction(serverSocket)
        except KeyboardInterrupt:
            serverSocket.close()


if __name__ == '__main__':
    main()
python networking tcp server
1个回答
0
投票

好吧,我解决了。我的ISP提供的调制解调器显然也是路由器。我有另一台路由器,我连接到这个端口并转发端口。只需要更改我的ISP路由器的设置,它工作正常。

© www.soinside.com 2019 - 2024. All rights reserved.