【问题标题】:Using python to connect sockets on 2 different machines使用 python 连接 2 台不同机器上的套接字
【发布时间】:2022-01-27 09:45:32
【问题描述】:

用 python 中的套接字连接 2 个 Pcs 是行不通的

这是服务器的代码

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

附加信息-我们都在连接到 wifi 的 2 台 PC 上运行 python 3.9,假设随机 ip 226.225.58.64 是他的 ip,它正在运行 server.py 两者都在最新版本的 pycharm 社区上并使用其终端

【问题讨论】:

  • 请定义“不起作用”。他们有联系吗?你试过调试吗?有哪些错误?为什么要标记websocket

标签: python python-3.x sockets websocket server


【解决方案1】:

我认为您的问题在于接收消息。消息正在正确发送,但您没有对消息进行解码,也没有将其打印出来。

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)

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

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多