ConnectionRefusedError: [Errno 111] Connection refused between laptop and raspberry pi using python

ConnectionRefusedError: [Errno 111] Connection refused between laptop and raspberry pi using python

我是套接字通信的初学者,想测试一下这段代码。

我写了相同的代码,但是当客户端和服务器都在我的笔记本电脑上并且正常工作时,我将服务器中的主机更改为 s.gethostname()。

服务器:笔记本电脑

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ''
port = 62402
s.bind((host,port))
s.listen(5)
while True:
  clientsocket, address = s.accept()
  print(f"connection from {address} has been established!")
  clientsocket.send(bytes("Welcome to the server!","utf-8"))

客户:raspberry pi

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 62402
s.connect((host,port))
msg = s.recv(1024)
print(msg.decode('utf-8')

错误

Traceback(most recent call last):
 File "/home/pi/Desktop/testting/client.py", line 6, in <module>
  s.connect((host,port))
ConnectionRefusedError: [Error 111] Connection refused

Connection refused 告诉我 [目标] 不接受连接。 我不认为 ´socket.gethostname()´ 可能 return 当前形式的笔记本电脑的主机名。 “print()”是什么 returns - 我敢打赌这是本地机器的主机名(创建连接的那个)。

一旦您知道要连接到哪里,可能会出错的地方:

  • 您的目标是否正在侦听端口 62402 上的连接?
  • 它的防火墙会允许这样的流量进入吗?