Python Socket不在本地网络上

时间:2015-04-05 21:08:02

标签: python-3.x client server wan python-sockets

我使用套接字编写了一个基本的服务器 - 客户端脚本,并且我的局域网上的一切正常,但是当我尝试连接到不在我的局域网中的客户端时,它不起作用。我也端口转发这些端口

这是服务器

###SERVER####


def ChatConnection():
    print('Waiting for a connection...\n')
    SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    HOST = ''
    PORT = 8989
    SOCKET.bind((HOST, PORT))
    SOCKET.listen(1)
    CONN, ADDR = SOCKET.accept()
    print('You can now chat')
    while True:
        MSG = str(input('\n[YOU]> '))
        while not MSG: MSG = str(input('\n[YOU]> '))
        CONN.send(MSG.encode())
        print('\nAwaiting reply...')
        REPLY = CONN.recv(4096).decode()
CONN.close()

这是客户

###CLIENT###



def ChatConnection():
    print('Waiting for a connection...\n')
    while True:
        try:
            HOST = SERVER EXTERNAL IP
            PORT = 8989
            SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            SOCKET.connect((HOST, PORT))
            print('You can now chat with server')
            print('\nWaiting for server...')
            while True:
                REPLY = SOCKET.recv(4096)
                print('\n[USER]> %s'%REPLY.decode())
                MSG = str(input('\n[YOU]> '))
                while not MSG: MSG = str(input('\n[YOU]> '))
                SOCKET.send(MSG.encode())
                print('\nAwaiting reply...')
            SOCKET.close()
    except Exception: pass

我需要做什么才能在WAN上运行?

1 个答案:

答案 0 :(得分:0)

确保端口转发工作,检查此项运行程序并尝试对公共IP进行端口扫描。
Port scanning tool

  • 尝试将HOST更改为0.0.0.0
  • 如果没有工作,请转到CMD并在脚本运行时写netstat -a
    搜索您正在收听的端口,并确保IP为0.0.0.0
  • 如果IP为0.0.0.0,请尝试关闭防火墙。