为什么我收到错误“连接被拒绝"?在 Python 中?(插座) [英] Why am I getting the error "connection refused" in Python? (Sockets)

查看:49
本文介绍了为什么我收到错误“连接被拒绝"?在 Python 中?(插座)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Sockets 的新手,请原谅我完全缺乏理解.

I'm new to Sockets, please excuse my complete lack of understanding.

我有一个服务器脚本(server.py):

I have a server script(server.py):

#!/usr/bin/python

import socket #import the socket module

s = socket.socket() #Create a socket object
host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port

s.listen(5) #Wait for the client connection
while True:
    c,addr = s.accept() #Establish a connection with the client
    print "Got connection from", addr
    c.send("Thank you for connecting!")
    c.close()

和客户端脚本(client.py):

and client script (client.py):

#!/usr/bin/python 

import socket #import socket module

s = socket.socket() #create a socket object
host = '192.168.1.94' #Host i.p
port = 12397 #Reserve a port for your service

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

我转到我的桌面终端并通过键入以下内容启动脚本:

I go to my desktop terminal and start the script by typing:

python server.py

之后,我转到我的笔记本电脑终端并启动客户端脚本:

after which, I go to my laptop terminal and start the client script:

python client.py

但我收到以下错误:

文件client.py",第 9 行,

File "client.py", line 9, in

s.connect((host,port))

s.connect((host,port))

文件/usr/lib/python2.7/socket.py",第 224 行,在 meth 中

File "/usr/lib/python2.7/socket.py", line 224, in meth

返回 getattr(self._sock,name)(*args)

return getattr(self._sock,name)(*args)

socket.error: [Errno 111] 连接被拒绝

socket.error: [Errno 111] Connection refused

我尝试过使用不同的端口号但无济于事.但是,我能够在客户端脚本中使用相同的 ip 和 gethostname() 方法获取主机名,并且可以 ping 桌面(服务器).

I've tried using different port numbers to no avail. However, I was able to get the host name using the same ip and the gethostname() method in the client script and I can ping the desktop (server).

推荐答案

代替

host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port

你应该试试

port = 12397 # Reserve a port for your service
s.bind(('', port)) #Bind to the port

这样监听套接字就不会受到太多限制.否则,监听只发生在一个接口上,而与本地网络无关.

so that the listening socket isn't too restricted. Maybe otherwise the listening only occurs on one interface which, in turn, isn't related with the local network.

一个例子可能是它只监听 127.0.0.1,这使得从不同的主机连接是不可能的.

One example could be that it only listens to 127.0.0.1, which makes connecting from a different host impossible.

这篇关于为什么我收到错误“连接被拒绝"?在 Python 中?(插座)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆