问题
为什么我收到了error: [Errno 57] Socket is not connected
,即使我已经初始化了套接字?完整的代码在 paste bin 上,但请随时查看我在此处提供的内容。
背景
我正在为套接字服务器创建一个基本的 GUI。我在使脚本的两个部分(GUI 和服务器)进行通信时遇到问题。服务器部分是按功能编写的,而 Tkinter GUI 是在 OOP 中。GUI 调用服务器的某些部分来运行。服务器完美无缺,但是每当我调用该函数send_msg
(使用套接字发送消息)时,我都会收到错误消息。
[Errno 57] Socket is not connected
代码
在GUI
__init__
方法中,我调用了start_up()
函数。该函数打开套接字并将其绑定到相应的地址。这是功能:
def start_up():
HOST = socket.gethostname()
PORT = 2468
print "HOST: %s" % (HOST)
print "PORT: %s" % (PORT)
print "\n"
print "-------------------------"
print "\n"
global s
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM )
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print "Socket Created"
try:
s.bind((HOST, PORT))
except socket.error, msg:
print "Bind failed. Error Code : " + str(msg[0]) + " Message " + str(msg[1])
sys.exit()
print "Socket Bind Complete"
"""
So by specifying 10, it means that if 10
connections are already waiting to be processed,
then the 11th connection request shall be rejected.
This will be more clear after checking socket_accept.
"""
s.listen(10)
print "Socket now listening"
每当我按下self.send
按钮时,它都会调用该class_send_msg
方法,该方法又会调用该send_msg(s)
函数。这是send_msg
代码:
def send_msg(s):
#Send some data to the remote server
message = app.message.get("0.0", END)
#set the whole string
s.sendall(message)
myHistory = open("history.txt", "a+")
myHistory.write(message)
最后,我收到的控制台消息(带有回溯):
HOST: ****.local
PORT: 2468
-------------------------
Socket Created
Socket Bind Complete
Socket now listening
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__
return self.func(*args)
File "/Volumes/****'S USB/Python Programs/Sockets/IM Project/Server/Server GUI InDev Class.py", line 160, in class_send_msg
send_msg(s)
File "/Volumes/****'s USB/Python Programs/Sockets/IM Project/Server/Server GUI InDev Class.py", line 97, in send_msg
s.sendall(message)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 57] Socket is not connected