python jsocket RuntimeError

时间:2016-02-11 18:36:12

标签: python jsocket

我试图使用jsocket在python中编写JSocket服务器。我使用了jsocket中的示例代码并对其进行了修改,以便服务器在收到客户端的消息后立即回复。当我的客户端尝试在" client.read_obj()"中收到响应时我得到一个例外。我的代码和下面的堆栈跟踪:

    #!/usr/bin/python

    import jsocket
    import logging

    logger = logging.getLogger("jsocket.testJSocket")

    class MyFactoryThread(jsocket.ServerFactoryThread):
        def __init__(self):
            super(MyFactoryThread, self).__init__()
            self.timeout = 2.0

        def _process_message(self, obj):  
            if obj!='':
                if obj ['message'] == 'new connection':
                    logger.info("new connection")
                    self.socket.send_obj({"dbResult": "result"})
                else:
                    logger.info(obj)
                    self.socket.send_obj({"dbResult": "result"})


    if __name__ == '__main__':
        import time
        import jsocket

        server = jsocket.ServerFactory(MyFactoryThread)
        server.timeout = 2.0
        server.start()

        time.sleep(1)
        client = jsocket.JsonClient()
        client.connect()
        client.send_obj({"message":"new connection"})

        client.read_obj()

        client.close()

        server.stop()
        server.join()

堆栈跟踪:

    pi@raspberrypi:~/programming/lights/comms $ sudo python testJSocket.py 
    [2016-02-11 20:28:54,475][DEBUG][tserver][start] Threaded Server has been started.
    [2016-02-11 20:28:55,479][DEBUG][jsocket_base][accept_connection] connection accepted, conn socket (127.0.0.1,39001)
    [2016-02-11 20:28:55,481][INFO][jsocket_base][connect] ...Socket Connected
    [2016-02-11 20:28:55,485][INFO][testJSocket][_process_message] new connection
    [2016-02-11 20:28:55,486][INFO][tserver][run] client connection broken, closing socket
    [2016-02-11 20:28:55,487][DEBUG][jsocket_base][_close_connection] closing the connection socket
    [2016-02-11 20:28:55,488][DEBUG][jsocket_base][_close_socket] closing main socket
    Traceback (most recent call last):
      File "testJSocket.py", line 39, in <module>
        client.read_obj()
      File "/usr/local/lib/python2.7/dist-packages/jsocket/jsocket_base.py", line 74, in read_obj
        size = self._msg_length()
      File "/usr/local/lib/python2.7/dist-packages/jsocket/jsocket_base.py", line 69, in _msg_length
        d = self._read(4)
      File "/usr/local/lib/python2.7/dist-packages/jsocket/jsocket_base.py", line 65, in _read
        raise RuntimeError("socket connection broken")
    RuntimeError: socket connection broken

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:0)

解决。我引用了错误的套接字。正确的代码:

        def _process_message(self, obj):

            if obj!='':
                if obj ['message'] == 'new connection':
                    logger.info("new connection")
                    self.send_obj({"dbResult": "result"})
                else:
                    logger.info(obj)
                    self.send_obj({"dbResult": "result"})