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

时间:2020-07-14 10:58:29

标签: python sockets

因此,我试图找出一种使用套接字制作基于终端的聊天应用程序的方法,并且我设法做到了。因为我只能在一台计算机上进行测试,所以我没有意识到它可能无法在其他计算机上运行。我的代码很简单:

# 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进行很多其他操作,但这是行不通的。服务器已启动并正在运行,但是客户端无法连接。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

我相信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
相关问题