Python:在GUI中调用Server函数时的Errno 57

时间:2013-03-24 20:04:28

标签: python macos oop sockets functional-programming

问题

为什么我收到error: [Errno 57] Socket is not connected,即使我已初始化套接字?完整代码为on 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

1 个答案:

答案 0 :(得分:2)

“s”是你的监听套接字。此套接字只接受新连接。您不应该在此套接字上发送数据。

您应该在“连接”上发送数据,这是您从调用s.accept()获得的套接字。

您可能需要重新构建代码才能实现此目的。