简体   繁体   English

使用 socket python 连接不同网络上的两台计算机

[英]Connect two computers on different networks using socket python

I am trying to connect two computers in different networks using the socket library.我正在尝试使用套接字库连接不同网络中的两台计算机。 On the first try I tried to connect two computers in the same network and it worked.第一次尝试时,我尝试连接同一网络中的两台计算机,并且成功了。 Then I tried to connect my friend's computer with mine in different networks, making various attempts and various searches I could not connect the two computers, I disabled the firewalls of both the server (my computer) and the client (computer of the my friend), but nothing, they don't connect.然后我尝试将我朋友的电脑连接到不同网络的我的电脑,进行各种尝试和各种搜索 两台电脑都无法连接,我禁用了服务器(我的电脑)和客户端(我朋友的电脑)的防火墙,但没有,他们不连接。 Below the source code of the client and server.下面是客户端和服务器的源代码。 What did I do wrong?我做错了什么? Server-side source code:服务端源码:

import socket
host = socket.gethostbyname(socket.gethostname())
port = 9999

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host,port))
sock.listen(1)
print(f"Server's ip: {host}\n Server's port: {port}")
print(f"Waiting for incoming connections...")
client, addr = sock.accept()
print(f"{addr} connected")

Client-side code:客户端代码:

import socket

host = "192.168.1.XXX"

port = 9999

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host,port))
print("You are connected!")

After some time python gives this error:一段时间后,python 出现此错误:

TimeoutError: [Errno 119] Connection timed out

好的,我解决了问题,我只需要从路由器设置中打开端口 9999。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM