Python 中的简单 TCP 服务器无法联机工作

Simple TCP Server in Python doesn't work online

我正在学习 this 教程,因为我不太了解 TCP 或一般的网络,它可以在本地主机上运行,​​但是当我将它切换到我的真实 IP 并让我的朋友在他的系统上试用客户端,它没有连接,给出错误:

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

如果因为“WinError”部分它在这里很重要,我在 Ubuntu,我的朋友在 Windows。

server.py

import socket

HOST = 'my ip'
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

client.py

import socket

HOST = '86.184.147.101'
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))

我认为这可能只是一些显而易见的事情,但我在 Whosebug 或互联网的其他部分找不到任何相关问题。干杯!

其中一个可能的问题是您没有在家中启用端口转发 router/firewall。确保您的家用路由器将端口 65432 转发到您 运行 服务器所在的本地计算机。 Google 您的路由器型号的“端口转发”,以了解如何配置它。

检查您是否能够使用 ping 命令 ping 到服务器。检查 computer/server 的 DNATing 规则。 另外,检查您的防火墙是否允许其他设备连接。