WebSocket emulation - Python server

Overview

SockJS-tornado server

SockJS-tornado is a Python server side counterpart of SockJS-client browser library running on top of Tornado framework.

Simplified echo SockJS server could look more or less like::

from tornado import web, ioloop from sockjs.tornado import SockJSRouter, SockJSConnection

class EchoConnection(SockJSConnection):
def on_message(self, msg):
self.send(msg)
if __name__ == '__main__':

EchoRouter = SockJSRouter(EchoConnection, '/echo')

app = web.Application(EchoRouter.urls) app.listen(9999) ioloop.IOLoop.instance().start()

(Take look at examples for a complete version).

Subscribe to SockJS mailing list for discussions and support.

SockJS-tornado API

SockJS provides slightly different API than tornado.websocket. Main differences are:

  1. Depending on transport, actual client connection might or might not be there. So, there is no _self.request_ and
    other tornado.web.RequestHandler properties.
  2. Changed open callback name to on_open to be more consistent with other callbacks.
  3. Instead of write_message, all messages are sent using send method. Just in case, send in tornado.web.RequestHandler
    sends raw data over the connection, without encoding it.
  4. There is handy broadcast function, which accepts list (or iterator) of clients and message to send.

Settings

You can pass various settings to the SockJSRouter, in a dictionary:

MyRouter = SockJSRouter(MyConnection, '/my', dict(disabled_transports=['websocket']))

Deployment

sockjs-tornado properly works behind haproxy and it is recommended deployment approach.

Sample configuration file can be found here.

If your log is full of "WARNING: Connection closed by the client", pass no_keep_alive as True to HTTPServer constructor:

HTTPServer(app, no_keep_alive=True).listen(port)

or:

app.listen(port, no_keep_alive=True)
Comments
  • WARNING:root:Write error on 11: [Errno 32] Broken pipe

    WARNING:root:Write error on 11: [Errno 32] Broken pipe

    Hi and thanks for the very good software. I'm here because lately I'm experiencing a strange problem with you lib (v0.0.5) and Python 2.7. It took me about a day to understand and reproduce it but now I've written a PoC demostrating the little bug.

    In few words: I've a software that acts something like a proxy: it receives data from the browser and sends them to a server and viceversa. Yesterday I noticed that in some condition I get strange errors from Chrome (22.0.1229.94): -[ Compressed bit must be 0 if no negotiated deflate-frame extension; One or more reserved bits are on: reserved2 = 1, reserved3 = 1; ... ]-

    IMHO the problem is that sockjs-tornado isn't thread-safe! In fact I use a thread to send data from the target server to the browser.

    This is the PoC:

    # coding=utf-8
    from tornado import web
    import tornado.ioloop
    import sockjs.tornado
    import threading
    
    # print the module name
    print sockjs.tornado
    
    
    class messageHandler(threading.Thread):
        def __init__(self, ws_conn):
            self.ws_conn = ws_conn
            threading.Thread.__init__(self)
    
        def run(self):
    
            print '   - Thread started!'
    
            try:
    
    
                print ' sending flood.......'
    
                txt = ('01020304050607080910111213' * 5000 + '\n') * 1000
                for x in txt.split("\n"):
                    self.ws_conn.send( x.decode("hex").decode("latin-1") )
    
                print 'sent'
    
    
            except Exception, why:
                print why
    
    
    
    class ProxerConnection(sockjs.tornado.SockJSConnection):
    
        def on_open(self, info):
            self._stage = 0
    
        def on_message(self, message):
            if self._stage == 0:
                # load a thread
                self._stage = 1
                print ' + Starting Thread...'
                self.thread = messageHandler(self)
                self.thread.setDaemon(True)
                self.thread.start()
    
            print message
    
    
    if __name__ == "__main__":
        #1. Create router (set the path for sockjs-client)
        gatewayRouter = sockjs.tornado.SockJSRouter(ProxerConnection, '/gateway', user_settings={'sockjs_url':'/gateway/sockjs-0.3.min.js'})
    
        import logging
        logging.getLogger().setLevel(logging.DEBUG)
    
        #2. Create Tornado application (router + sockjs-client)
        app = tornado.web.Application(
                gatewayRouter.urls
        )
    
        #3. Make Tornado app listen on port 8001
        app.listen( 8001 )
    
        #4. Start IOLoop
        tornado.ioloop.IOLoop.instance().start()
    
    

    This is what I get when the thread starts the flood:

    <module 'sockjs.tornado' from '/usr/lib/python2.7/site-packages/sockjs_tornado-0.0.5-py2.7.egg/sockjs/tornado/__init__.pyc'>
    
    INFO:root:200 GET /gateway/info (192.168.1.247) 0.86ms
     + Starting Thread...
       - Thread started!
      sending flood......
    
    WARNING:root:Write error on 11: [Errno 32] Broken pipe
    sent
    
    

    Client-side: -[ Compressed bit must be 0 if no negotiated deflate-frame extension ]-

    To test it you should:

    • start the server
    • connect to the server and send a message now the server will start the thread and the flood begins. In few seconds you should get some error from chrome (and maybe also with FF). sometimes everything works well. (this also let me think that the problem is something with the thread). Moreover if I put the flood directly in the "on_message" event I don't have problems.

    thanks again, Stefano

    opened by shen139 13
  • exception thrown for xhr-streaming protocol

    exception thrown for xhr-streaming protocol

    I'm receiving the following errors in sockjs-tornado log, and it seems like (from the highlighted blocks) that @asynchrounous decorator is needed on on_message() method? However, I am not making any asynchronous calls in on_message() at all.

    Additional details: this actually happened on the latest Chrome browser, which should have used websocket to connect, but failed, then switched to use xhr-streaming. This failure of using native websocket has happened a few times, but not often. I am not sure if this has anything to do with the error below. Also, sockjs-tornado instance is running behind HAProxy 1.5-dev17.

    ERROR:root:XHR incoming Traceback (most recent call last): File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/sockjs/tornado/transports/xhr.py", line 85, in post session.on_messages(messages) File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/sockjs/tornado/session.py", line 426, in on_messages self.conn.on_message(msg) File "chat_server.py", line 996, in on_message self.register(msg['id'], msg['msg']) File "chat_server.py", line 650, in register self.send(setup_msg) File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/sockjs/tornado/conn.py", line 49, in send self.session.send_message(message, binary=binary) File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/sockjs/tornado/session.py", line 324, in send_message self.send_jsonified(proto.json_encode(msg), stats) File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/sockjs/tornado/session.py", line 342, in send_jsonified self.handler.send_pack('a[%s]' % msg) File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/sockjs/tornado/transports/xhrstreaming.py", line 40, in send_pack self.write(message + '\n') File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/tornado/web.py", line 489, in write raise RuntimeError("Cannot write() after finish(). May be caused " RuntimeError: Cannot write() after finish(). May be caused by using async operations without the @asynchronous decorator. ERROR:root:Uncaught exception POST /sockjs/365/y2jr5vz6/xhr_send (127.0.0.1) HTTPRequest(protocol='http', host='www.mysite.com', method='POST', uri='/sockjs/365/y2jr5vz6/xhr_send', version='HTTP/1.1', remote_ip='127.0.0.1', body='["{"id":"3f4c54be769e1163","msg":"blahblah"}"]', headers={'Origin': 'https://www.mysite.com', 'Content-Length': '118', 'Accept-Language': 'en-US,en;q=0.8', 'Accept-Encoding': 'gzip,deflate,sdch', 'X-Forwarded-For': '127.0.0.1', 'Host': 'www.mysite.com', 'Accept': '/', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,;q=0.3', 'Connection': 'close', 'X-Forwarded-Proto': 'https', 'Referer': 'https://www.mysite.com/chat/3f4c54be769e1163', 'Content-Type': 'application/xml'}) Traceback (most recent call last): File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/tornado/web.py", line 1042, in _execute getattr(self, self.request.method.lower())(_args, __kwargs) File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/sockjs/tornado/transports/xhr.py", line 88, in post session.close() File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/sockjs/tornado/session.py", line 385, in close self.handler.send_pack(proto.disconnect(code, message)) File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/sockjs/tornado/transports/xhrstreaming.py", line 40, in send_pack self.write(message + '\n') File "/home/cilia/envs/.virtualenvs/chat/local/lib/python2.7/site-packages/tornado/web.py", line 489, in write _raise RuntimeError("Cannot write() after finish(). May be caused " RuntimeError: Cannot write() after finish(). May be caused by using async operations without the @asynchronous decorator.* ERROR:root:500 POST /sockjs/365/y2jr5vz6/xhr_send (127.0.0.1) 2.04ms INFO:root:200 POST /sockjs/365/y2jr5vz6/xhr_streaming (127.0.0.1) 0.59ms

    opened by cilia 7
  • Incompatible with Tornado 6.0

    Incompatible with Tornado 6.0

    Tornado 6.0 removes tornado.web.asynchronous, which is used by sockjs-tornado.

    As Tornado 6.0 is the current stable version for Python3, this means installing sockj-tornado on Python3 does not work by default.

    opened by jbms 5
  • Socket errors when using WSS

    Socket errors when using WSS

    Hello, We just switched over from using socket.io and tornadio2 to using sockjs-tornado. Thanks for the recommendation btw. There are lots of performance improvements.

    We've been running it through our integration for a few days now and are seeing these in our logs. They look very similar to the things we were seeing in socket.io. These are four separate tracebacks from two incidents. They only happen when we use WSS. We are seeing about 10 such incidents during a five hour integration run. Any ideas?

    2012-05-15 00:59:18,052 WARNING:Write error on 191: [Errno 14] Bad address
    2012-05-15 00:59:18,054 ERROR:Error in periodic callback
    Traceback (most recent call last):
       File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/periodic.py", line 68, in _run
         next_call = self.callback()
       File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/session.py", line 396, in _heartbeat
         self.handler.send_pack(proto.HEARTBEAT)
       File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/transports/websocket.py", line 83, in send_pack
         self.write_message(message)
       File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 169, in write_message
         self.ws_connection.write_message(message, binary=binary)
       File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 577, in write_message
         self._write_frame(True, opcode, message)
       File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 567, in _write_frame
         self.stream.write(frame)
       File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 219, in write
         self._handle_write()
       File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 647, in _handle_write
         super(SSLIOStream, self)._handle_write()
       File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 518, in _handle_write
         self.socket.fileno(), e)
     AttributeError: 'NoneType' object has no attribute 'fileno'
    
    
    2012-05-15 00:59:18,223 ERROR:Uncaught exception, closing connection.
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 304, in wrapper
        callback(*args)
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 661, in _on_frame_data
        self._receive_frame()
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 580, in _receive_frame
        self.stream.read_bytes(2, self._on_frame_start)
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 180, in read_bytes
        self._check_closed()
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 535, in _check_closed
        raise IOError("Stream is closed")
    IOError: Stream is closed
    2012-05-15 00:59:18,224 ERROR:Exception in callback <tornado.stack_context._StackContextWrapper object at 0xfc9f70>
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/ioloop.py", line 399, in _run_callback
        callback()
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 304, in wrapper
        callback(*args)
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 661, in _on_frame_data
        self._receive_frame()
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 580, in _receive_frame
        self.stream.read_bytes(2, self._on_frame_start)
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 180, in read_bytes
        self._check_closed()
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 535, in _check_closed
        raise IOError("Stream is closed")
    IOError: Stream is closed
    

    Second incident

    2012-05-15 01:03:53,559 WARNING:Write error on 3: [Errno 32] Broken pipe
    2012-05-15 01:03:53,560 ERROR:Uncaught exception in /sj/333/sjodg8q4/websocket
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 297, in wrapper
        return callback(*args, **kwargs)
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/transports/websocket.py", line 29, in open
        self.stream.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
    AttributeError: 'NoneType' object has no attribute 'setsockopt'
    2012-05-15 01:03:53,561 ERROR:Uncaught exception, closing connection.
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 304, in wrapper
        callback(*args)
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/httpserver.py", line 250, in _on_headers
        self.request_callback(self._request)
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/web.py", line 1362, in __call__
        handler._execute(transforms, *args, **kwargs)
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 145, in _execute
        self.ws_connection.accept_connection()
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 509, in accept_connection
        self._accept_connection()
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 551, in _accept_connection
        self._receive_frame()
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 580, in _receive_frame
        self.stream.read_bytes(2, self._on_frame_start)
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 180, in read_bytes
        self._check_closed()
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 535, in _check_closed
        raise IOError("Stream is closed")
    IOError: Stream is closed
    2012-05-15 01:03:53,563 ERROR:Exception in callback <tornado.stack_context._StackContextWrapper object at 0x1e018e8>
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/ioloop.py", line 399, in _run_callback
        callback()
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 304, in wrapper
        callback(*args)
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/httpserver.py", line 250, in _on_headers
        self.request_callback(self._request)
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/web.py", line 1362, in __call__
        handler._execute(transforms, *args, **kwargs)
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 145, in _execute
        self.ws_connection.accept_connection()
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 509, in accept_connection
        self._accept_connection()
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 551, in _accept_connection
        self._receive_frame()
      File "/usr/local/lib/python2.7/site-packages/sockjs_tornado-0.0.4-py2.7.egg/sockjs/tornado/websocket.py", line 580, in _receive_frame
        self.stream.read_bytes(2, self._on_frame_start)
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 180, in read_bytes
        self._check_closed()
      File "/usr/local/lib/python2.7/site-packages/tornado-2.2.1-py2.7.egg/tornado/iostream.py", line 535, in _check_closed
        raise IOError("Stream is closed")
    IOError: Stream is closed
    2012-05-15 01:03:53,569 DEBUG:Ignoring IOError in safe_finish()
    
    opened by aychedee 5
  • SockJS 0.2? Or 0.1 full compliance?

    SockJS 0.2? Or 0.1 full compliance?

    With SockJS 0.2 release, will sockjs-tornado support it any time soon?

    I found that you didnt include any examples for testing sockjs protocol. I created my own script using sockjs and well, test is failing in some cases. It would be great to see it all green ;) #0.1 full results

    test_greeting (main.BaseUrlGreeting) ... ok test_notFound (main.BaseUrlGreeting) ... ok test_basic (main.ChunkingTest) ... ok test_options (main.ChunkingTest) ... ok test_transport (main.EventSource) ... ok test_no_callback (main.HtmlFile) ... ok test_transport (main.HtmlFile) ... ok test_cacheability (main.IframePage) ... ok test_invalidUrl (main.IframePage) ... ok test_queriedUrl (main.IframePage) ... ok test_simpleUrl (main.IframePage) ... ok test_versionedUrl (main.IframePage) ... ok test_content_types (main.JsonPolling) ... ok test_invalid_json (main.JsonPolling) ... ok test_no_callback (main.JsonPolling) ... ok test_transport (main.JsonPolling) ... FAIL test_closeSession (main.Protocol) ... ERROR test_simpleSession (main.Protocol) ... ok test_closeSession_another_connection (main.ProtocolQuirks) ... HANGS UP test_anyValue (main.SessionURLs) ... ok test_ignoringServerId (main.SessionURLs) See Protocol.test_simpleSession for explanation. ... ok test_invalidPaths (main.SessionURLs) ... ok test_broken_json (main.WebsocketHixie76) ... ERROR test_close (main.WebsocketHixie76) ... FAIL test_empty_frame (main.WebsocketHixie76) ... ok test_headersSanity (main.WebsocketHixie76) ... ok test_reuseSessionId (main.WebsocketHixie76) ... ok test_transport (main.WebsocketHixie76) ... ok test_disabledTransport (main.WebsocketHttpErrors) ... ok test_httpMethod (main.WebsocketHttpErrors) ... ok test_invalidConnectionHeader (main.WebsocketHttpErrors) ... ok test_invalidMethod (main.WebsocketHttpErrors) ... ok test_verifyOrigin (main.WebsocketHttpErrors) ... ok test_broken_json (main.WebsocketHybi10) ... ok test_close (main.WebsocketHybi10) ... ERROR test_firefox_602_connection_header (main.WebsocketHybi10) ... ok test_headersSanity (main.WebsocketHybi10) ... ok test_transport (main.WebsocketHybi10) ... ok test_content_types (main.XhrPolling) ... ok test_invalid_json (main.XhrPolling) ... ok test_invalid_session (main.XhrPolling) ... ok test_jsessionid (main.XhrPolling) ... ok test_options (main.XhrPolling) ... ok test_transport (main.XhrPolling) ... FAIL test_options (main.XhrStreaming) ... ok test_transport (main.XhrStreaming) ... ok

    Now 0.2

    test_greeting (main.BaseUrlGreeting) ... ok test_notFound (main.BaseUrlGreeting) ... ok test_response_limit (main.EventSource) ... ok test_transport (main.EventSource) ... ok test_abort_xhr_polling (main.HandlingClose) ... ERROR test_abort_xhr_streaming (main.HandlingClose) ... HANGS UP test_close_frame (main.HandlingClose) ... HANGS UP test_close_request (main.HandlingClose) ... ok test_no_callback (main.HtmlFile) ... ok test_response_limit (main.HtmlFile) ... ok test_transport (main.HtmlFile) ... ok test_cacheability (main.IframePage) ... ok test_invalidUrl (main.IframePage) ... ok test_queriedUrl (main.IframePage) ... ok test_simpleUrl (main.IframePage) ... ok test_versionedUrl (main.IframePage) ... ok test_basic (main.InfoTest) ... FAIL test_disabled_websocket (main.InfoTest) ... FAIL test_entropy (main.InfoTest) ... ERROR test_options (main.InfoTest) ... FAIL test_xhr_server_decodes (main.JSONEncoding) ... ok test_xhr_server_encodes (main.JSONEncoding) ... ok test_content_types (main.JsonPolling) ... ok test_invalid_json (main.JsonPolling) ... ok test_no_callback (main.JsonPolling) ... ok test_transport (main.JsonPolling) ... ok test_closeSession (main.Protocol) ... ERROR test_simpleSession (main.Protocol) ... ok test_close (main.RawWebsocket) ... ERROR test_transport (main.RawWebsocket) ... ERROR test_anyValue (main.SessionURLs) ... ok test_ignoringServerId (main.SessionURLs) See Protocol.test_simpleSession for explanation. ... ok test_invalidPaths (main.SessionURLs) ... ok test_broken_json (main.WebsocketHixie76) ... ERROR test_close (main.WebsocketHixie76) ... FAIL test_empty_frame (main.WebsocketHixie76) ... ok test_headersSanity (main.WebsocketHixie76) ... ok test_reuseSessionId (main.WebsocketHixie76) ... ok test_transport (main.WebsocketHixie76) ... ok test_httpMethod (main.WebsocketHttpErrors) ... ok test_invalidConnectionHeader (main.WebsocketHttpErrors) ... ok test_invalidMethod (main.WebsocketHttpErrors) ... FAIL test_verifyOrigin (main.WebsocketHttpErrors) ... ok test_broken_json (main.WebsocketHybi10) ... ok test_close (main.WebsocketHybi10) ... ERROR test_firefox_602_connection_header (main.WebsocketHybi10) ... ok test_headersSanity (main.WebsocketHybi10) ... ok test_transport (main.WebsocketHybi10) ... ok test_content_types (main.XhrPolling) ... ok test_invalid_json (main.XhrPolling) ... ok test_invalid_session (main.XhrPolling) ... ok test_jsessionid (main.XhrPolling) ... ok test_options (main.XhrPolling) ... ok test_transport (main.XhrPolling) ... ok test_options (main.XhrStreaming) ... ok test_response_limit (main.XhrStreaming) ... FAIL test_transport (main.XhrStreaming) ... ok

    Analysis

    some failures are common, what's interesting is that some tests are now fully working!

    • ProtocolQuirks.test_closeSession_another_connection - (present only in 0.1) no idea what's the issue here. It just won't die.
    • Protocol.test_closeSession - times out (not sure if this is an issue with my test script?)
    • WebsocketHixie76.test_broken_json - this one has some broken dependencies (module import error) on my machine (which most likely means - dependency changed a little) but even after fixing it, doesn't seem to work. Which may or may not be due to the fact, that dependency (https://github.com/liris/websocket-client/) behavior changed.
    • WebsocketHybi10.test_close - again close seems to be an issue
    • JsonPolling.test_transport - fails in 0.1, but WORKS fine in 0.2!
    • WebsocketHixie76.test_close - again with close. AssertionError: 'h' != u'c[3000,"Go away!"]'
    • XhrPolling.test_transport - fails in 0.1, but WORKS fine in 0.2!
    • HandlingClose.test_abort_xhr_polling - time out. Aborting, closing and stuff seems to be the main issue.
    • InfoTest.* - this one is new in 0.2, not implemented and should be part of the API.
    • Protocol.test_closeSession - time out.
    • RawWebsocket.* - this is something that cannot be implemented with current API (websocket without framing, heartbeats and stuff).
    • WebsocketHttpErrors.test_invalidMethod - for invalid methods it wants not only 405 but also something in 'allow' tag. Doesn't check what though, but anyway it is empty.
    • XhrStreaming.test_response_limit - it stopped working. Apparently, response_limit setting should not count needed by IE 2049 header ('h'*2048+'\n'). At least that's what node is using. Smells fishy.

    Let's summarize this essay

    So what is really not working? Something's wrong with closing. RawWebsockets require implementation. New Info (/info) default endpoint as well. Rest seems to be of low priority.

    opened by 23doors 5
  •  New release of sockjs-tornado

    New release of sockjs-tornado

    I noticed that the latest - and only - release of sockjs-tornado is v1.0.0 and it's from more than 2 years ago (April 3rd, 2013).

    In the mean time there seems to have been lots of commits and pull requests merged.

    I looked for information online but could not understand why no new release has been cut. Is there another place I should look at for stable releases of Tornado or should I just use the latest code on Master?

    opened by ChrisJamesC 4
  • Compatibility with Sock-js 1.0.0

    Compatibility with Sock-js 1.0.0

    Is sockjs-tornado compatible with sock-js 1.0.0? Last sock-js version v1.0.0-beta.12 is from Feb 2015.

    Especially the heartbeats since 0.4.0 are interesting: https://github.com/sockjs/sockjs-protocol/wiki/Heartbeats-and-SockJS

    opened by jnsflint 4
  • xhr.py and xhrstreaming.py accepts generic arguments upon connection.

    xhr.py and xhrstreaming.py accepts generic arguments upon connection.

    Tornado allows request parameters to come from path section of the URL not only from query section (?name1=value1&name2=value2)

    For example if Tornado handler url pattern is "/api/kernels/(?P<kernel_id>\w+-\w+-\w+-\w+-\w+)/shell" and real request comes for "/api/kernels/2-3-4-2-4/shell" handler will be executed with named argument kernel_id='2-3-4-2-4'.

    Unfortunately sockjs-tornado doesn't have this feature for the connection set up request - all parameters should be passed in a query section of URL. This change tries to fix that.

    opened by rageTrue 4
  • Expose origin header to ConnectionInfo object

    Expose origin header to ConnectionInfo object

    There were added some headers to the info object in #20. The docstrings says something about the origin header, but the header is not included in the _exposed_headers list. But I would like to get it later in my on_open method. (Or can you tell me another smart way to check on which URL the client was when he established the connection?) Thank you very much.

    opened by normanjaeckel 4
  • How to set request.argument ?

    How to set request.argument ?

    The First: https://sockjs-tornado.readthedocs.org/en/latest/mod_session.html#sockjs.tornado.session.ConnectionInfo

    The Second: https://github.com/mrjoes/sockjs-tornado/blob/master/sockjs/tornado/conn.py#L28-L31

    But I don't know how pass some data to request.argument...

    And I just tried... But failed.

    conn = new SockJS('http://chatsocial.me/chat?argu=some');
    

    What should I do?

    opened by omgbbqhaxx 4
  • Active connections time out while shipping bulk data

    Active connections time out while shipping bulk data

    The transport send_pack() implementations detach from the session before data transmission is complete. (They either don't use RequestHandler.flush(), or don't request a callback.) When the pack takes a long time to transfer, the SessionContainer can then expire the session while the client is still receiving. The client finishes receiving, tries to open the next connection, fails, and reports "Server lost session".

    This occurs reliably with XhrPollingTransport and a multi-megabyte pack. It may also affect streaming transports when they hit the amount_limit, but I haven't tested this.

    opened by bgilbert 4
  • Please push tag for v1.0.7

    Please push tag for v1.0.7

    opened by stuarteberg 0
  • socks-tornado does not support path kwargs

    socks-tornado does not support path kwargs

    SockJS-Tornado is really cool project and I'm very glad to use it. But Ive got the problem related to the path kwargs . For example:

    Everything works fine If I don't use named path kwargs:

    ChatRouter = sockjs.tornado.SockJSRouter(ChatHandler, '/chat')

    If I change the prefix like this:

    ChatRouter = sockjs.tornado.SockJSRouter(ChatHandler, '/chat/(?P<room_id>[a-z0-9]{2,20})')

    I will get the error When I try to connect to the chat:

    Traceback (most recent call last):
      File "/Users/rlashchenkov/projects/env_msg/lib/python3.5/site-packages/tornado/web.py", line 1467, in _execute
        result = method(*self.path_args, **self.path_kwargs)
    TypeError: get() got an unexpected keyword argument 'room_id'
    
    opened by XxxUNIXxxX 0
  • Happened easily AssertionError at websocket.py when connection over 20 clients.

    Happened easily AssertionError at websocket.py when connection over 20 clients.

    When I try to send data to each connection, it is easily to occur AssertionError when sending.

    Exception in thread Thread-1:
    Traceback (most recent call last):
      File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/threading.py", line 914, in _bootstrap_inner
        self.run()
      File "fto.py", line 38, in run
        self.send_message()
      File "fto.py", line 79, in send_message
        c.send(arr)
      File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sockjs/tornado/conn.py", line 49, in send
        self.session.send_message(message, binary=binary)
      File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sockjs/tornado/session.py", line 322, in send_message
        self.send_jsonified(proto.json_encode(bytes_to_str(msg)), stats)
      File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sockjs/tornado/session.py", line 337, in send_jsonified
        self.handler.send_pack('a[%s]' % msg)
      File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sockjs/tornado/transports/websocket.py", line 86, in send_pack
        self.write_message(message, binary)
      File "/usr/local/lib/python3.5/site-packages/tornado/websocket.py", line 252, in write_message
        return self.ws_connection.write_message(message, binary=binary)
      File "/usr/local/lib/python3.5/site-packages/tornado/websocket.py", line 783, in write_message
        message = self._compressor.compress(message)
      File "/usr/local/lib/python3.5/site-packages/tornado/websocket.py", line 548, in compress
        assert data.endswith(b'\x00\x00\xff\xff')
    AssertionError
    
    opened by dewsxc 3
  • ImportError: cannot import name 'errors'

    ImportError: cannot import name 'errors'

    On server run, this is the trace returned :

    python server.py 
    Traceback (most recent call last):
      File "server.py", line 10, in <module>
        from sockjs.tornado import SockJSRouter
      File "/Users/mohit/anaconda/envs/py34/lib/python3.4/site-packages/sockjs/__init__.py", line 20, in <module>
        from sockjs.route import get_manager, add_endpoint
      File "/Users/mohit/anaconda/envs/py34/lib/python3.4/site-packages/sockjs/route.py", line 11, in <module>
        from sockjs.transports import handlers
      File "/Users/mohit/anaconda/envs/py34/lib/python3.4/site-packages/sockjs/transports/__init__.py", line 3, in <module>
        from .jsonp import JSONPolling
      File "/Users/mohit/anaconda/envs/py34/lib/python3.4/site-packages/sockjs/transports/jsonp.py", line 8, in <module>
        from .base import StreamingTransport
      File "/Users/mohit/anaconda/envs/py34/lib/python3.4/site-packages/sockjs/transports/base.py", line 2, in <module>
        from aiohttp import errors
    ImportError: cannot import name 'errors'
    
    opened by mohit-jcc 0
  • Installing with PyPI brings wrong version

    Installing with PyPI brings wrong version

    I'm installing this in my project using pip and version 1.0.3 (lastest shown here: https://pypi.python.org/pypi/sockjs-tornado)

    However I noticed that I don't get the latest files. In particular I'm affected by the problem that this commits fixes: https://github.com/mrjoes/sockjs-tornado/commit/6c745eeed0afde54b990c3187a78c311bd52b5a2

    When I look at the code after the pip installation, those lines are still there which also matches the behavior i see in my server.

    Is there a way to update the pip repo so that the actual code from 1.0.3 is there?

    opened by CoDanny 0
Owner
Serge S. Koval
Serge S. Koval
Django Channels HTTP/WebSocket server

daphne Daphne is a HTTP, HTTP2 and WebSocket protocol server for ASGI and ASGI-HTTP, developed to power Django Channels. It supports automatic negotia

Django 1.9k Dec 31, 2022
This websocket program is for data transmission between server and client. Data transmission is for Federated Learning in Edge computing environment.

websocket-for-data-transmission This websocket program is for data transmission between server and client. Data transmission is for Federated Learning

null 9 Jul 19, 2022
Benchmark a WebSocket server's message throughput ⌛

?? WebSocket Benchmarker ⌚ Message throughput is how fast a WebSocket server can parse and respond to a message. Some people consider this to be a goo

Andrew Healey 24 Nov 17, 2022
image stream publish server over websocket

Image Stream Push Server 简介 通过浏览器网页实时查看图像处理结果。 环境 运行程序需要安装一下python依赖: tornado: 用于创建http及websocket服务; opencv-contrib-python: 用于图像数据源获取及图像处理。 使用 进入到src目

MrError404 1 Nov 4, 2021
Synci - Learning project to create a websocket based client server messaging application

Synci Learning project to create a websocket based client server messaging appli

null 2 Jan 13, 2022
WebSocket implementation in Python built on top of websockets python library. Similar to Node.js's ws.

ws WebSocket implementation in Python built on top of websockets python library. Similar to Node.js's ws. Basic usage. server.py import ws server = w

AceExpert 7 Jun 27, 2022
WebSocket and WAMP in Python for Twisted and asyncio

Autobahn|Python WebSocket & WAMP for Python on Twisted and asyncio. Quick Links: Source Code - Documentation - WebSocket Examples - WAMP Examples Comm

Crossbar.io 2.4k Jan 4, 2023
Library for building WebSocket servers and clients in Python

What is websockets? websockets is a library for building WebSocket servers and clients in Python with a focus on correctness and simplicity. Built on

Aymeric Augustin 4.3k Jan 4, 2023
WebSocket client for Python

websocket-client The websocket-client module is a WebSocket client for Python. It provides access to low level APIs for WebSockets. All APIs are for s

null 3.1k Jan 2, 2023
一款为 go-cqhttp 的正向 WebSocket 设计的 Python SDK

Nakuru Project 一款为 go-cqhttp 的正向 WebSocket 设计的 Python SDK 在 kuriyama 的基础上改动 项目名来源于藍月なくる,图标由せら绘制 食用方法 将 nakuru 文件夹移至 Python 的 Lib/site-packages 目录下。

null 35 Dec 21, 2022
Using python-binance to provide websocket data to freqtrade

The goal of this project is to provide an alternative way to get realtime data from Binance and use it in freqtrade despite the exchange used. It also uses talipp for computing

null 58 Jan 1, 2023
alien.py - Python interface to websocket endpoint of ALICE Grid Services

alien.py - Python interface to websocket endpoint of ALICE Grid Services Quick containerized testing: singularity

Adrian Sevcenco 6 Dec 14, 2022
wssh ("wish") is a command-line utility/shell for WebSocket inpsired by netcat.

wssh ("wish") is a command-line utility/shell for WebSocket inspired by netcat

Jeff Lindsay 256 Nov 16, 2022
Whatsapp Clone using django, django-channels and websocket

whatsapp-clone Whatsapp Clone using django, django-channels and websocket Features : Signup/Login One on One personal chat with other user Some screen

Anshu Pal 14 Dec 25, 2022
Minecraft WebSocket

Minecraft-WebSocket Pythonでマインクラフトと通信します。 紹介動画 推奨設定 Minecraft Windows Edition (Education Edition) 1.17 以上 Python 3系(3.8.2で動作確認済み) 必要なモジュール ・asyncio ・w

Roii.py 2 Jul 7, 2022
Tetri5 - Multiplayer Websocket Backend

Tetri5 - Multiplayer Websocket Backend This repository is the backend of the multiplayer portion of the Tetri5 game client. It uses the python websock

Giovani Rodriguez 1 Dec 10, 2022
AWS API Gateway Websocket Asynchronous Notifications Pusher

AWS API Gateway Websocket Asynchronous Pusher Fast AWS API Gateway websockets notifications' pusher using Python AsyncIO for managing asynchronous and

OBytes 5 May 15, 2022
Discord.py Connect to Discord voice call with websocket

Discord.py Connect to Discord voice call with websocket

WoahThatsHot 3 Apr 22, 2022
A websocket client for Source Filmmaker intended to trasmit scene and frame data to other applications.

SFM SOCK A websocket client for Source Filmmaker intended to trasmit scene and frame data to other applications. This software can be used to transmit

KiwifruitDev 2 Jan 8, 2022