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.

WebSockets with Python! Yay!
http://dev.enekoalonso.com/2010/05/22/more-websockets-now-with-python/
This comment was originally posted on Twitter
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 !
circuits.web (1) as of revision fe3965b21fe2 now implements a working WebSockets Server:
https://bitbucket.org/prologic...
This allows you to have a WebSockets server that sits alongside your application server (no need for a separate server, etc). This will be integrated into the circuits.web namespace before the next release.
cheers
James
1. http://bitbucket.org/prologic/…/
The WebSocket protocol changed, to include a quite weird handshake. I’ve modified your example to work with the new protocol, posted on StackOverflow:
http://stackoverflow.com/questions/4372657/websocket-handshake-problem-using-python-server/5282208#5282208
Thanks for sharing, dbr.
“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?
@tom- you need to DITCH google chrome!
I’m just sayin…
This should work with the latest version of Google chrome.
If not try the updated Firefox. That will work for sure.
I got it to work in Google Chrome. I had no issues, there must be something you did wrong.