繁体   English   中英

在两台不同的机器上使用 python 连接 sockets

[英]Using python to connect sockets on 2 different machines

在 python 中将 2 个与 sockets 连接起来是行不通的

这是服务器的代码

import socket
host_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_socket.bind((socket.gethostbyname(socket.gethostname()), 9999))
host_socket.listen(5)

while True:
    client, address = host_socket.accept()
    print(f"Connection to {address} established")
    print(client)
    client.send(bytes("cheese", 'utf-8'))

和客户端的代码

import socket
print(socket.gethostbyname(socket.gethostname()))
client_socket = socket.create_connection(('226.225.58.64', 9999))
print("Connected with the server on port 5000")
while True:
    try:
        message = client_socket.recv(4096)
    except ConnectionResetError:
        print("Connection closed by the server")
    except TimeoutError:
        pass

Additional information- We both are running python 3.9 on 2 PCs connected to wifi, assume random ip 226.225.58.64 is his ip, which is running server.py both are on the latest version of pycharm community and using its terminal

我认为您的问题在于接收消息。 消息正在正确发送,但您没有解码消息并且也没有打印它。

while True:
    try:
        message = client_socket.recv(4096)
        message = message.decode("utf-8")#since you sent it in utf-8 encoding, you have to decode it in utf-8 only
        print(message)

使用此代码并检查它是否适合您。

暂无
暂无

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

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