[英]Trying to connect socket to server in different networks raises WinError 10060
I am trying to establish a socket connection, therefore I coded and tried this example code with server.py and client.py:我正在尝试建立套接字连接,因此我使用 server.py 和 client.py 编写并尝试了此示例代码:
server.py:服务器.py:
import socket
port = 5674
ip = socket.gethostbyname(socket.gethostname())
s = socket.socket()
s.bind((ip, port))
s.listen(2)
print('Server is ready')
while True:
client, address = s.accept()
print('New connection to {}'.format(address))
client.send('You are connected to the server!'.encode('utf-8'))
client.py:客户端.py:
import socket
ip = '' # enter ip address of server
port = 5674
s = socket.socket()
s.connect((ip, port))
msg = s.recv(1024).decode('utf-8')
print(msg)
Trying to run this on one machine will work absolutely fine.尝试在一台机器上运行它绝对可以正常工作。
Running on different machines in different networks will give the following error-message in client.py:在不同网络的不同机器上运行会在 client.py 中给出以下错误消息:
Traceback (most recent call last): File "D:/Python/01programs/SocketTest/client.py", line 7, in s.connect((ip, port)) TimeoutError: [WinError 10060] Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach einer >bestimmten Zeitspanne nicht richtig reagiert hat, oder die hergestellte Verbindung war fehlerhaft, da >der verbundene Host nicht reagiert hat
回溯(最近一次调用):文件“D:/Python/01programs/SocketTest/client.py”,第 7 行,在 s.connect((ip, port)) TimeoutError: [WinError 10060] Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach einer >bestimmten Zeitspanne nicht richtig reagiert hat, oder die hergestellte Verbindung war fehlerhaft, da >der verbundene Host nicht reagiert hat
-> shortened in English: try to connect failed because the connected host did not respond in time
-> 英文缩写:尝试连接失败,因为连接的主机没有及时响应
What is going wrong with this socket connection?这个套接字连接出了什么问题? I would say it seems like client is not able to find server and is not able to connect because of this.
我会说客户端似乎无法找到服务器并且因此无法连接。
What part is wrong and how to fix?哪个部分有问题,如何修复? Thanks for help!
感谢帮助!
PS: I already read many questions related to this problem but none of them seemed to help in my case. PS:我已经阅读了许多与此问题相关的问题,但似乎没有一个对我的情况有帮助。
If you trying to accesses your server not from the same host, you can't.如果您尝试访问的服务器不是来自同一主机,则无法访问。 you need to run the server not in local-host mode, change the server ip bind to "0.0.0.0" and it should work.
您需要不在本地主机模式下运行服务器,将服务器 ip 绑定更改为“0.0.0.0”,它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.