Search code examples
websockettornadoweb2py

web2py / websockets - the example in websocket_messaging.py doesn't work?


I copied exactly as is, the two actions in the gluon/contrib/websocket_messaging.py file.

controllers/debug.py:

def index():
    form=LOAD('debug','ajax_form',ajax=True)
    script=SCRIPT('''
        jQuery(document).ready(function(){
          var callback=function(e){alert(e.data)};
          if(!web2py_websocket('ws://127.0.0.1:8888/realtime/mygroup',callback))
            alert("html5 websocket not supported by your browser, try Google Chrome");
        });
    ''')
    return dict(form=form, script=script)

def ajax_form():
    form=SQLFORM.factory(Field('message'))
    if form.accepts(request,session):
        from gluon.contrib.websocket_messaging import websocket_send
        websocket_send(
            'http://127.0.0.1:8888',form.vars.message,'mykey','mygroup')
    return form

views/debug/index.html:

{{extend 'layout.html'}}
{{=form}}
{{=script}}

But when I connect to the website I see the following error message:

Firefox can't establish a connection to the server at ws://127.0.0.1:8888/realtime/mygroup

I start the server like this:

python gluon/contrib/websocket_messaging.py -k mykey -p 8888

and the message there is:

WARNING:tornado.access:403 GET /realtime/mygroup (127.0.0.1) 0.55ms

but I can see any message I send, it just doesn't pop up through the alert function.

As a disclaimer I'm complete new to java and websockets so any help is appreciated.


Solution

  • so the problem was that my websocket_messaging.py was missing the following:

    def check_origin( self , origin ):
        return True
    

    in the class DistributeHandler(tornado.websocket.WebSocketHandler)

    even though the https://github.com/web2py/web2py/blob/master/gluon/contrib/websocket_messaging.py had this correctly implemented. (look at line 149)

    I am running web2py 2.11.2 so no idea if this is expected or not and I also updated through the web2py admin interface not by downloading a new web2py instance. Not sure if that could've caused the problem.

    Either way solved!