首页 > 解决方案 > Simple Client - Server scripts don't work, Timeout error 10060 when attempting to connect

问题描述

I've looked at many similar questions yet I can't figure out why connections are never established, they simply timeout. I've seen some questions where it's suggested a firewall (windows firewall) issue could be blocking me but I'm not so sure, I've tried disabling the firewall on both machines but the problem persists. There are also python rules which allows incoming and outgoing connections on both machines.

I've checked my router settings but I can't find anything there to suggest port forwarding is disabled etc.

I keep one of my devices on my home network and the other on my mobile data hotspot to simulate devices on separate networks. I've swapped around these devices.

I've used wireshark to inspect packets, I can see packets leaving on either network but never being received.

client.py

import socket

HOST, PORT = SERVERS-EXTERNAL-IP, 65000 #Tried a variety of ports
data = "Hello very cool message"

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data + "\n", "utf-8"))


print(f"Sent:     {data}")

server.py

import socket

PORT = 65000
HOST = socket.gethostname() #Tried other things like '', ''localhost' etc
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(5)


print("Listening")
c, addr = sock.accept()
print("Accepted")
data = c.recv(1024)

sock.close()

client.py result:

Traceback (most recent call last):
  File "client.py", line 15, in <module>
    sock.connect((HOST, PORT))
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

server.py result:

Listening

Any suggestions as to why I'm facing this issue?

标签: pythonpython-3.xsocketsclient-server

解决方案


好的,我设法让它工作。与我之前的想法相反,没有设置端口转发。

为了解决这个问题,我为我的服务器创建了一个静态本地 IP 地址,并在我的路由器设置中创建了一个端口转发规则,以将特定端口定向到服务器的静态 IP。以下网站非常有用:

https://portforward.com

还要感谢@SteffenUllrich 以正确的方式指导我。


推荐阅读