Monthly Archives: February 2013

A super-simple chat app with AngularJS, SockJS and node.js

12 February 2013

We’re planning to move to a more advanced JavaScript library at PythonAnywhere. jQuery has been good for us, but we’re rapidly reaching a stage where it’s just not enough.

There are a whole bunch of JavaScript MVC frameworks out there that look tempting — see TodoMVC for an implementation of a simple app in a bunch of them. We’re asking the people we know and trust which ones are best, but in the meantime I had a look at AngularJS and knocked up a quick chat app to see how easy it would be. The answer was “very”.

Here’s the client-side code:

<html ng-app>
<script src=""></script>
<script src=""></script>

    var sock = new SockJS('');
    function ChatCtrl($scope) {
        $scope.messages = [];
        $scope.sendMessage = function() {
            $scope.messageText = "";

        sock.onmessage = function(e) {



<div ng-controller="ChatCtrl">
        <li ng-repeat="message in messages">{{message}}</li>

    <form ng-submit="sendMessage()">
        <input type="text" ng-model="messageText" placeholder="Type your message here" />
        <input type="submit" value="Send" />


Then on the server side I wrote this server (in node.js because I’ve moved to Shoreditch and have ironic facial hair it was easy to copy, paste and hack from the SockJS docs — I’d use Tornado if this was on PythonAnywhere):

var http = require('http');
var sockjs = require('sockjs');

var connections = [];

var chat = sockjs.createServer();
chat.on('connection', function(conn) {
    var number = connections.length;
    conn.write("Welcome, User " + number);
    conn.on('data', function(message) {
        for (var ii=0; ii < connections.length; ii++) {
            connections[ii].write("User " + number + " says: " + message);
    conn.on('close', function() {
        for (var ii=0; ii < connections.length; ii++) {
            connections[ii].write("User " + number + " has disconnected");

var server = http.createServer();
chat.installHandlers(server, {prefix:'/chat'});
server.listen(9999, '');

And that's it! It basically does everything you need from a simple chat app. Definitely quite impressed with AngularJS. I'll try it in some of the other frameworks we evaluate and post more here.