如何使用Python套接字连接到同一网络上的另一台计算机

2024-03-28 12:24:32 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图找到一种使用套接字制作基于终端的聊天应用程序的方法,我成功地做到了这一点。因为我只能在一台计算机上测试它,所以我没有意识到它可能无法在不同的计算机上工作。我的代码如下所示:

# Server
import socket
HOST = "0.0.0.0"
PORT = 5555

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    while True:
        conn, addr = s.accept()
        with conn:
            print("Connected to", addr)
            data = conn.recv(1024)
            print("Received:", data.decode())
            conn.sendall(data)
# Client
import socket
HOST = "192.168.0.14"
PORT = 5555

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b"Hello this is a connection")
    data = s.recv(1024)
print("Received:", data.decode())

我尝试过将ip更改为0.0.0.0,使用gethostname还有很多其他功能,但都不起作用。服务器已启动并正在运行,但客户端无法连接。有人能帮我吗


Tags: importhostdatastreamportas计算机with
1条回答
网友
1楼 · 发布于 2024-03-28 12:24:32

我相信0.0.0.0意味着从任何地方连接,这意味着您必须允许端口5555通过防火墙

enter image description here

在客户端和服务器中使用localhost作为地址,而不是0.0.0.0

我刚刚使用localhost对服务器和客户机测试了您的代码,您的程序运行正常

服务器:

Connected to ('127.0.0.1', 53850)
Received: Hello this is a connection

客户:

Received: Hello this is a connection

如您所见,我所更改的只是服务器和客户端上的地址。如果这不起作用,那么在你的计划之外有一些东西阻碍你成功。这可能是权限问题,或者另一个程序正在端口5555上侦听

server.py

# Server
import socket
HOST = "0.0.0.0"
HOST = "localhost"
PORT = 5555

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    while True:
        conn, addr = s.accept()
        with conn:
            print("Connected to", addr)
            data = conn.recv(1024)
            print("Received:", data.decode())
            conn.sendall(data)

if __name__ == '__main__':
    pass

client.py

# Client
import socket
HOST = "localhost"
PORT = 5555

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b"Hello this is a connection")
    data = s.recv(1024)
print("Received:", data.decode())

if __name__ == '__main__':
    pass

相关问题 更多 >