Cheerypy and ws4py, hearder 'upgrade' is not defined

Vincent Le Goff <[email protected]>
Newsgroups gmane.comp.python.cherrypy
Message-ID <CAFO53fQcQ=3e943Aeu5dg7N7LR0xzd776PHouDe+fJw5b7zH9A@mail.gmail.com>
Hi everyone,

I was trying to use ws4py with CherryPy to have WebSockets usable on this
server.  Right away, however, I ran into an error.  I had to slightly
modify the example given in cherrypyserver so it would work.  Although it
doesn't, so perhaps I modified the wrong thing.  Attached you will find
this file.  I guess you should be able to run it directly, assuming you
have cherrypy and ws4py installed.


CheerPy version: 5
ws4py version: 0.3.5
Testing broser: Mozilla Firefox 44.

When running the script, no error occurs.  But when my browser attempts to
connect to http://127.0.0.1:9000, a 500 error is displayed.  The log in the
console displays a full tracebck which ends with:

ws4py.exc.HandshakeError: Header Upgrade is not defined

I remember running into this error previously, but I can't remember in what
circumstances.  I'm not running behind a proxy.  Is it an error in my
configuration?

Thank you,

Vincent

-- 
You received this message because you are subscribed to the Google Groups "cherrypy-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cherrypy-users+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/[email protected]
To post to this group, send email to cherrypy-users-/JYPxA39Uh5TLH3MbocFF+G/[email protected]
Visit this group at https://groups.google.com/group/cherrypy-users.
For more options, visit https://groups.google.com/d/optout.
cherrypyserver.py (text/x-python, 4.2 KB)
# -*- coding: utf-8 -*-
__doc__ = """
WebSocket within CherryPy is a tricky bit since CherryPy is
a threaded server which would choke quickly if each thread
of the server were kept attached to a long living connection
that WebSocket expects.

In order to work around this constraint, we take some advantage
of some internals of CherryPy as well as the introspection
Python provides.

Basically, when the WebSocket handshake is complete, we take over
the socket and let CherryPy take back the thread that was
associated with the upgrade request.

These operations require a bit of work at various levels of
the CherryPy framework but this module takes care of them
and from your application's perspective, this is abstracted.

Here are the various utilities provided by this module:

 * WebSocketTool: The tool is in charge to perform the
                  HTTP upgrade and detach the socket from
                  CherryPy. It runs at various hook points of the
                  request's processing. Enable that tool at
                  any path you wish to handle as a WebSocket
                  handler.

 * WebSocketPlugin: The plugin tracks the instanciated web socket handlers.
                    It also cleans out websocket handler which connection
                    have been closed down. The websocket connection then
                    runs in its own thread that this plugin manages.

Simple usage example:

.. code-block:: python
    :linenos:

    import cherrypy
    from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
    from ws4py.websocket import EchoWebSocket

    cherrypy.config.update({'server.socket_port': 9000})
    WebSocketPlugin(cherrypy.engine).subscribe()
    cherrypy.tools.websocket = WebSocketTool()

    class Root(object):
        @cherrypy.expose
        def index(self):
            return 'some HTML with a websocket javascript connection'

        @cherrypy.expose
        def ws(self):
            pass

    cherrypy.quickstart(Root(), '/', config={'/ws': {'tools.websocket.on': True,
                                                     'tools.websocket.handler_cls': EchoWebSocket}})


Note that you can set the handler class on per-path basis,
meaning you could also dynamically change the class based
on other envrionmental settings (is the user authenticated for ex).
"""
import cherrypy
from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from ws4py.websocket import EchoWebSocket
import random
cherrypy.config.update({'server.socket_host': '127.0.0.1',
                        'server.socket_port': 9000})
WebSocketPlugin(cherrypy.engine).subscribe()
cherrypy.tools.websocket = WebSocketTool()

class Root(object):
    @cherrypy.expose
    @cherrypy.tools.websocket(on=False)
    def ws(self):
        return """<html>
    <head>
      <script type='application/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'> </script>
      <script type='application/javascript'>
        $(document).ready(function() {
          var ws = new WebSocket('ws://127.0.0.1:9000/');
          ws.onmessage = function (evt) {
             $('#chat').val($('#chat').val() + evt.data + '\\n');
          };
          ws.onopen = function() {
             ws.send("Hello there");
          };
          ws.onclose = function(evt) {
            $('#chat').val($('#chat').val() + 'Connection closed by server: ' + evt.code + ' \"' + evt.reason + '\"\\n');
          };
          $('#chatform').submit(function() {
             ws.send('%(username)s: ' + $('#message').val());
             $('#message').val("");
             return false;
          });
        });
      </script>
    </head>
    <body>
    <form action='/echo' id='chatform' method='get'>
      <textarea id='chat' cols='35' rows='10'></textarea>
      <br />
      <label for='message'>%(username)s: </label><input type='text' id='message' />
      <input type='submit' value='Send' />
      </form>
    </body>
    </html>
    """ % {'username': "User%d" % random.randint(0, 100)}

    @cherrypy.expose
    def index(self):
        cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler))

cherrypy.quickstart(Root(), '/', config={'/': {'tools.websocket.on': True,
                                               'tools.websocket.handler_cls': EchoWebSocket}})
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.