More WebSockets, now with Python!

A couple of weeks ago, Tim and I worked on a little game/demo using WebSockets and C# (I haven’t been able to put it online since I do not have a Windows server). It was a lot of fun and we were able to see the potential of WebSockets and how much internet can will change in the next few years because of them.

Today I spent a couple of hours researching and implementing a WebSocket solution that I could run in my linux servers, and I found this very nice tutorial for creating a Python WebSockets server: http://yz.mit.edu/wp/web-sockets-tutorial-with-simple-python-server/

So I took that code and modified to create a very, very basic chat, that broadcasts received messages to all connected clients. You can try it here (as long as the python server is still up): http://enekoalonso.com/research/html5/websockets/python/

Here is the client code:

	var form = document.getElementById('form');
	var msg = document.getElementById('msg');
	var output = document.getElementById('serveroutput');

	var s = new WebSocket("ws://"+window.location.hostname+":9876/");
	s.onopen = function(e) {
		console.log("opened");
		out('Connected.');
	}
	s.onclose = function(e) {
		console.log("closed");
		out('Connection closed.');
	}
	s.onmessage = function(e) {
		console.log("got: " + e.data);
		out(e.data);
	}

	form.onsubmit = function(e) {
		e.preventDefault();
		msg.value = '';
		window.scrollTop = window.scrollHeight;
	}

	function sendMsg() {
		s.send(msg.value);
	}

	function out(text) {
		var el = document.createElement('p');
		el.innerHTML = text;
		output.appendChild(el);
	}

	msg.focus();

And the server code:

#!/usr/bin/env python

import socket, threading

# httphost = "localhost:8888"
# sockethost = "localhost:9876"
httphost = "enekoalonso.com"
sockethost = "enekoalonso.com:9876"

def handle(s, addr):
  handsake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nWebSocket-Origin: http://%s\r\nWebSocket-Location: ws://%s/\r\nWebSocket-Protocol: sample\r\n\r\n" % (httphost, sockethost)
  s.send(handsake)
  data = s.recv(1024)
  lock = threading.Lock()

  while 1:
    data = s.recv(1024)
    if not data: break
    print 'Data from', addr, ':', data
    lock.acquire()
    [conn.send(data) for conn in clients]
    lock.release()

  print 'Client closed:', addr
  lock.acquire()
  clients.remove(s)
  lock.release()
  s.close()

def start_server():
	s = socket.socket()
	s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	s.bind(('', 9876))
	s.listen(1)
	while 1:
	  conn, addr = s.accept()
	  print 'Connected by', addr
	  clients.append(conn)
	  threading.Thread(target = handle, args = (conn,addr)).start()

clients = []
start_server()

Check the live demo (be aware WebSockets are only supported by Google Chrome right now): http://enekoalonso.com/research/html5/websockets/python/
Open a few tabs and send some text. You should see it appearing in all of them. It will also work if you open the page in multiple browser windows or even if you open the page in different computers.

Related Posts:

1 Tweet 6 Other Comments

10 thoughts on “More WebSockets, now with Python!

  1. dany

    Thanks for your blog ! I have not used any thread and this is what I get :

    while 1:
    ssock, saddr = s.accept()
    print(‘Connected by’, saddr)
    data = ssock.recv(4096)
    while 1 :
    data = s.recv(1024)
    print(‘Data from’, saddr, ‘:’, data)
    ssock.sendall(data)

    Unfortunately, this does not work ! Why ?

    It is the same if I add the handshake :

    while 1:
    ssock, saddr = s.accept()
    print(‘Connected by’, saddr)
    handsake = “HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nWebSocket-Origin: http://%s\r\nWebSocket-Location: ws://%s/\r\nWebSocket-Protocol: sample\r\n\r\n” % (httphost, sockethost)
    s.send(handsake)
    data = ssock.recv(4096)
    while 1 :
    data = s.recv(1024)
    print(‘Data from’, saddr, ‘:’, data)
    ssock.sendall(data)

    Do you know why ? In both cases, I get the same following error : [Errno 10057] socket is not connected, no address.
    Is it because I use no thread ?

    Thanks for your help !

  2. Tom

    “It will also work if you open the page in multiple browser windows or even if you open the page in different computers.”

    I am having difficulty getting this to work with Google Chrome – any suggestions guys?

  3. Makram Chehayeb

    Hi I have a python server on my machine binding a socket to its
    IP ADDRESS and to a port that I chose(50001) I would like to build a
    simple web application that allows me only to send a string from a
    websocket to my raw TCP socket what should I do? I am actually trying to implement a web Remote Control for my nao robot any help will be much appreciated

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType