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

Posted on 12 February 2013 in JavaScript, Programming, PythonAnywhere

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>
<head>
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>

<script> var sock = new SockJS('http://192.168.0.74:9999/chat'); function ChatCtrl($scope) { $scope.messages = []; $scope.sendMessage = function() { sock.send($scope.messageText); $scope.messageText = ""; };

sock.onmessage = function(e) { $scope.messages.push(e.data); $scope.$apply(); }; } </script>

</head>

<body>

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

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

</body> </html>

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) { connections.push(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, '0.0.0.0');

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.