使用 Python 套接字的 PC(Linux) 和 RPi 之间的连接被拒绝

Connection refused between PC(Linux) and RPi using Python socket

我遇到了一个大问题,我无法解决。我尝试检查多个答案但没有结果。主要任务:PC 和 Raspberry Pi 之间的连接使用 TCP/IP 以太网。
我的代码如下所示:
服务器:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),1234))
s.listen(5)

while True:
    client, address = s.accept()
    print(f"Connection from {address} succesfully!")
    client.send(bytes("Hello!", "utf-8"))
s.close()

客户:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(),1234))
Message = "HeloWorld!"
s.send(byte(Message))

s.close()

The error is: ConnectionRefusedError: [Errno 111] Connection refused

我该怎么办?

看来你把函数搞混了。
socket.gethostname():

Return a string containing the hostname of the machine where the Python interpreter is currently executing.

您可以查看:

print socket.gethostname()

但是socket.connect() function wants an address (which depends on protocol family). Thus you probably want to use IP addresses of your hosts or resolve domain names of hosts to IP addresses through socket.gethostbyname().

你还有几个错别字。要使其工作(客户端和服务器都在同一主机上的情况的注释行),请尝试:
服务器:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.bind((socket.gethostbyname(socket.gethostname()), 31337))

# suppose 192.168.0.2 is IP of one of your server's network interfaces
s.bind(("192.168.0.2", 31337))
s.listen(5)

while True:
    client, address = s.accept()
    print "Connection from ", address, ", message:", client.recv(32)
    client.send(bytes("WTF"))
s.close()

客户:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.connect((socket.gethostbyname(socket.gethostname()), 31337))
s.connect(("192.168.0.2", 31337))
s.send(bytes("Hello, World!"))
print "Message from server: ", s.recv(32)
s.close()