迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中 ConnectionRefusedError: [Errno 111] Connection Refused 错误

作者:迹忆客 最近更新:2023/05/16 浏览次数:

此错误表明客户端无法连接到服务器脚本系统上的端口。 既然能ping通服务器,应该不会吧。

这可能是由多种原因引起的,例如到目的地的路由不正确。 第二种可能性是您的客户端和服务器之间有防火墙,它可能在服务器上,也可能在客户端上。

不应该有任何路由器或防火墙可能会停止通信,因为根据您的网络地址,服务器和客户端都应该在同一个局域网上。


为什么 ConnectionRefusedError: [Errno 111] Connection refused 在 Python 中发生

当客户端由于无效的 IP 或端口而无法访问服务器,或者地址不唯一且已被另一台服务器使用时,会出现此错误。

服务器未运行时也会出现连接拒绝错误,因此客户端无法访问服务器,因为服务器应首先接受连接。

代码示例:

# server code
import socket

s = socket.socket()
host = socket.gethostname()
port = 1717
s.bind((host, port))

s.listen(5)
while True:
    c,addr = s.accept()
    print("Got connection ", addr)
    c.send("Meeting is at 10am")
    c.close()
# client code
import socket

s = socket.socket()
host = '192.168.1.2'
port = 1717

s.connect((host,port))
print(s.recv(1024))
s.close

输出:

socket.error: [Errno 111] Connection refused

如何解决Python中 ConnectionRefusedError: [Errno 111] Connection refused 错误

尽量使接收套接字尽可能易于访问。 也许可访问性只会发生在一个界面上,这不会影响局域网。

另一方面,一种情况可能是它专门侦听地址 127.0.0.1,从而无法与其他主机建立连接。

代码示例:

import socket

s = socket.socket()
host = socket.gethostname()
port = 1717
s.bind(('', port))

s.listen(5)
while True:
    c,addr = s.accept()
    print("Got connection ", addr)
    c.send("The Meeting is at 10 am")
    c.close()
import socket

s = socket.socket()
host = socket.gethostname()
port = 1717
s.bind(('', port))

s.connect((host, port))
print(s.recv(1024))
s.close()

输出:

Got connection('192.168.1.2')
The meeting is at 10 am

当您运行命令 python server.py 时,您将收到消息 Got connection。 同时当你运行命令 python client.py 时,你会收到一条来自服务器的消息。

DNS 解析可能是此问题背后的另一个原因。 由于 socket.gethostname() 返回主机名,如果操作系统无法将其转换为本地地址,则会返回错误。

Linux操作系统可以通过添加一行来编辑主机文件。

host = socket.gethostname()
port = 1717
s.bind((host,port))
Use gethostbyname
host = socket.gethostbyname("192.168.1.2")
s.bind((host, port))

因此,您必须在客户端和服务器端使用相同的技术来访问主机。 例如,您可以在客户案例中应用上述程序。

您还可以通过本地主机名 hostnamehost = socket.gethostname() 或本地主机的特定名称 host = socket.gethostbyname("localhost") 进行访问。

host = socket.gethostname()
s.connect((host, port))
host = socket.gethostbyname("localhost")
s.connect((host, port))

总结

当客户端无法连接到服务器时,会出现 Python 中的 ConnectionRefusedError。 几个原因包括客户端不知道 IP 或端口地址,以及当客户端想要连接时服务器未运行。

上面提到的几种方法可以解决此连接问题。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便