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

时间:2019-02-08 19:54:49

标签: python networking tcp server

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

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

Server.py

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.py

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()

1 个答案:

答案 0 :(得分:0)

好的,我解决了。我的ISP提供的调制解调器显然也是路由器。我有另一台路由器,并且已连接到该路由器并从中转发端口。只需更改我的ISP路由器的设置,它就可以正常工作。