Websockets tutorial/example with pywebsocket

9 years ago

As everyone already knows, Google Chrome now supports websockets. In essence, this allows you to keep a connection open with a webserver indefinitely (analogous to typical sockets) and send data bi-directionally. Unfortunately Chrome is the only browser currently supporting this, but I'm pretty sure this will change.

So I decided to give this a try and experiment a bit with it. This is my step by step process on getting a web page opening a websocket to a server and receiving the server's date and time every second. It is based on an article by Joe Armstrong, though he uses Erlang for the server, while I decided to follow the easy road and use Google's pywebsocket - an apache module (uses mod_python) that allows you to create handlers for websocket connections in a easy-to-use fashion. The code also contains a way to start a standalone server (i.e. not requiring apache) for testing purposes.

So here are the steps I took to get this working:

1. Create a web page This is the code I borrowed from Joe, though slightly modified to fit my purposes (it requires jquery, by the way):


<html>
  <head>
    <script src="jquery-1.3.2.min.js"></script> 
    <script>
      $(document).ready(function() {
        var ws;

        if ("WebSocket" in window) { 
          debug("Horray you have web sockets. Trying to connect..."); 
          ws = new WebSocket("ws://localhost:9998/echo");

          ws.onopen = function() { 
            // Web Socket is connected. You can send data by send() method. 
            debug("connected..."); 
            ws.send("hello from the browser"); 
            ws.send("more from browser"); 
          };

          run = function() { 
            var val=$("#i1").val(); 
            // read the entry 
            $("#i1").val(");
            // and clear it 
            ws.send(val);
            // tell erlang 
            return true;
            // must do this 
          };

          ws.onmessage = function (evt) { 
            //alert(evt.data); 
            var data = evt.data; 
            var i = data.indexOf("!"); 
            var tag = data.slice(0,i); 
            var val = data.slice(i+1); $("#" + tag).html(val); 
          };

          ws.onclose = function() { 
            debug(" socket closed"); 
          }; 
        } else { 
          alert("You have no web sockets"); 
        };

        function debug(str) { 
          $("#debug").append("<p>" +  str); 
        };
      }); 
    </script>
    </head>
    
    <body>
      <h1>Interaction experiment</h1>
      <h2>Debug</h2> <div id="debug"></div>

      <fieldset> 
        <legend>Clock</legend> 
        <div id="clock">I am a clock</div> 
      </fieldset>
    </body>
  </html> 

2. Download and install pywebsocket Checkout the code with svn checkout http://pywebsocket.googlecode.com/svn/trunk/ pywebsocket-read-only

Then do python setup.py build and sudo python setup.py install inside the src folder. This will install it into your python environment.

3. Being lazy, means we will change an example handler The way pywebsocket works is delegating the connections to something they call handlers. In the pywebsocket-read-only/src/example folder you will find a file named echo_wsh.py. They have this convention where handlers are named <entry_point>_wsh.py. This means that when you later call (from your web page) the url http://localhost:9998/echo the server will delegate the processing of that connection to that file.

I modified that file to something like this:


# Copyright 2009, Google Inc. 
# All rights reserved. # 
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions are 
# met: 
# * Redistributions of source code must retain the above copyright 
# notice, this list of conditions and the following disclaimer. 
# * Redistributions in binary form must reproduce the above 
# copyright notice, this list of conditions and the following disclaimer 
# in the documentation and/or other materials provided with the 
# distribution. #     
# * Neither the name of Google Inc. nor the names of its 
# contributors may be used to endorse or promote products derived from 
# this software without specific prior written permission. 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from mod_pywebsocket import msgutil 
from datetime import datetime 
import time

_GOODBYE_MESSAGE = 'Goodbye'

def web_socket_do_extra_handshake(request): 
  print 'Connected.' pass
  # Always accept.

def web_socket_transfer_data(request): 
  while True: 
    time.sleep(1) 
    date = datetime.now() 
    try: 
      line = msgutil.receive_message(request) 
    except Exception, e:
      raise e 
    #print 'Got something: %s' % line 
    #msgutil.send_message(request, line) 
    msgutil.send_message(request, 'clock!%s' % date) 
    #if line == _GOODBYE_MESSAGE:
    #return 

So basically whenever a new connection is made to this entry point, a call to web_socket_do_extra_handshake is made. After that, web_socket_transfer_data is called and it's your responsibility to create the loop that receives messages and handles the flow (as you can see in the commented lines). I don't care about that right now, since I only want to push the date and time to the client every second.

4. Start the standalone server Go to the pywebsocket-read-only/src/mod_pywebsocket folder and run the following command:

sudo python standalone.py -p 9998 -w ../example/

This will start the server in port 9998 and use the handlers directory specified by the -w option. That is where our echo_wsh.py lives.

5. Test it :D So now open your browser (remember, only chrome supports websockets currently) and open the html file your created in the beginning. Voilá, server's date and time every second in the clock div.