Simple WebSocket Server in Python

This sample uses Tornado, which is a socket server module for Python. I found this sample code here. I modified the python script very slightly, and pretty much completely overhauled the html page.

 

To install Tornado, it's easiest to do it via the python package manager (pip). So here is how I installed both pip and tornado from the command line:

sudo apt-get install python-pip

pip install tornado

 

 

Once you've done that you can download and unzip the files:

 python-socket-server-and-client.zip 

Or, if you'd like to review the code before downloading, look down the page. It's only two files and they are both pretty simple.

 

To try it out just unzip the files in a directory, then cd to that directory and enter:

python websocket-server.py

 

This will start the web socket server. Now open up your browser and enter this in the url bar: localhost:9090

 

If you want to run the client from a different machine (not the one that is running the websocket server), you'll have to adjust the 'host' variable in index.html

 

Here is the code for the server (websocket-server.py) :


import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.template

class MainHandler(tornado.web.RequestHandler):
def get(self):
loader = tornado.template.Loader(".")
self.write(loader.load("index.html").generate())

class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'connection opened...'
self.write_message("The server says: 'Hello'. Connection was accepted.")

def on_message(self, message):
self.write_message("The server says: " + message + " back at you")
print 'received:', message

def on_close(self):
print 'connection closed...'

application = tornado.web.Application([
(r'/ws', WSHandler),
(r'/', MainHandler),
(r"/(.*)", tornado.web.StaticFileHandler, {"path": "./resources"}),
])

if __name__ == "__main__":
application.listen(9090)
tornado.ioloop.IOLoop.instance().start()

 

 

And here is index.html

<!DOCTYPE html>
<html>
<head>
<title>WebSockets Client</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
Enter text to send to the websocket server:
<div id="send">
<input type="text" id="data" size="100"/><br>
<input type="button" id="sendtext" value="send text"/>
</div>
<div id="output"></div>
</body>
</html>
<script>

jQuery(function($){

if (!("WebSocket" in window)) {
alert("Your browser does not support web sockets");
}else{
setup();
}


function setup(){

// Note: You have to change the host var
// if your client runs on a different machine than the websocket server

var host = "ws://localhost:9090/ws";
var socket = new WebSocket(host);
//console.log("socket status: " + socket.readyState);

var $txt = $("#data");
var $btnSend = $("#sendtext");

$txt.focus();

// event handlers for UI
$btnSend.on('click',function(){
var text = $txt.val();
if(text == ""){
return;
}
socket.send(text);
$txt.val("");
});

$txt.keypress(function(evt){
if(evt.which == 13){
$btnSend.click();
}
});

// event handlers for websocket
if(socket){

socket.onopen = function(){
//alert("connection opened....");
}

socket.onmessage = function(msg){
showServerResponse(msg.data);
}

socket.onclose = function(){
//alert("connection closed....");
showServerResponse("The connection has been closed.");
}

}else{
console.log("invalid socket");
}

function showServerResponse(txt){
var p = document.createElement('p');
p.innerHTML = txt;
document.getElementById('output').appendChild(p);
}


}

});

</script>