🏠 Home   🕵🏽‍♂️ About

Realtime chat using Node.js and Socket.IO Fri 2 Mar, 2012

I thought I'd post about my first meaningful Node.js app. It's the much used realtime chat example, using socket.io. It's comprised of a simple client and a server that maintains a list of connected users so that messages can be attributed to their author. As an aside, it blows my mind that you can have realtime two-way communication between clients in significantly less that 100 lines of code. Pretty cool.

So here are the bits that matter. I've just used a static file server to serve the index.html rather than setting up routing, as that wasn't the point of this exercise. The server handles the standard socket events.

server.js

var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs');

app.listen(8888);

function handler (req, res) {
fs.readFile(__dirname + req.url, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading page');
}
res.writeHead(200);
res.end(data);
});
}

io.sockets.on('connection', function(socket){
socket.on('set name', function(name) {
socket.set('name', name, function() {
socket.broadcast.send(name + ' has joined the conversation')
});
});

socket.on('message', function(data) {
socket.get('name', function(err, name) {
socket.broadcast.send(name + ' says: ' + data);
});
});

socket.on('disconnect', function() {
socket.get('name', function(err, name) {
socket.broadcast.send(name + ' has left the conversation.');
});
});
});

The client has a button to connect to the server, a prompt asking for your name, and a simple form to submit messages.

client.html

<script src="/jquery/1.4.4/jquery.min.js" ></script>
<script src="/socket.io/socket.io.js" ></script>

<script type="text/javascript">
$(document).ready(function() {
$('#connect-button').click(function() {

$('#form-container').show(300);
var socket = io.connect('<hostname>', {port: 8888});

socket.on('connect', function() {
socket.emit('set name', prompt('What is your name?'));
socket.on('ready', function() {
$('#connect-message').append($('<p>').text('Connected...'));
});
});

$('#simple-form').submit(function(e) {
e.preventDefault();
var textObj = $('#data');
var msg = textObj.val();
textObj.val('');
socket.emit('message', msg);
});

socket.on('message', function(msg) {
$('#simple-form').append($('<p>').text(msg));
});

socket.on('disconnect', function(msg) {
$('#simple-form').append($('<p>').text(msg));
});
});
});
</script>

And that's all there is to it. This is obviously super minimal, and in no way actually usable, but it does what I wanted it to, and was a nice little primer on Node and socket.io. Enjoy.