Getting Started with Socket.IO and Node.js
Node.js is not the cure for everything, however, it can certainly makes working with Websockets very easy when using the Socket.io library. Using websockets you can easily build realtime applications and even multi-player games. Today I’ll show you how to easily build a simple chat program using Node.js and Socket.io.
Note: To go through this article you will need to have Node.js installed and working correctly. You will also need some sort of text editor, I’ll be using WebStorm but anything you wish to use should work. Some of the code in this article has been modified from this excellent source: http://book.mixu.net/ch13.html
On you computer create a new folder somewhere convenient called: chat. Inside that folder you can add two files called: app.js and index.html
Let’s fill in the app.js file first.
var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
socketio.listen(server).on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});The above code is pretty bare minimum for a chat server. The server sends the index.html file and listens for any incoming websockets. If you were to send a message like “hi” the format would look something like the following:
{"name":"message","args":["hi"]}The index.html page is also very minimal and looks like the following:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$(function(){
var iosocket = io.connect();
iosocket.on('connect', function () {
$('#incomingChatMessages').append($('<li>Connected</li>'));
iosocket.on('message', function(message) {
$('#incomingChatMessages').append($('<li></li>').text(message));
});
iosocket.on('disconnect', function() {
$('#incomingChatMessages').append('<li>Disconnected</li>');
});
});
$('#outgoingChatMessage').keypress(function(event) {
if(event.which == 13) {
event.preventDefault();
iosocket.send($('#outgoingChatMessage').val());
$('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val()));
$('#outgoingChatMessage').val('');
}
});
});
</script>
</head>
<body>
Incoming Chat: <ul id="incomingChatMessages"></ul>
<br />
<input type="text" id="outgoingChatMessage">
</body>
</html>The webpage is not very attractive but it works. Open two browsers preferably ones that support WebSockets (Chrome or Safari will work).
The next step is to install socket.io by doing the following in a terminal (or command prompt):
$ npm install socket.io
Run the app.js file:
$ node app.js
Now with your two browsers go to the following path and try it out: http://localhost:8080/
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)







Comments
Herry Johnson replied on Tue, 2012/06/12 - 12:57pm
1) Catch it and actually handle it. This means whatever failed, you have to make it work. Maybe by trying again, maybe be providing a default value.
2) If you cannot to #1, then you should not catch the exception in the first place. Or, if you do catch it, wrap it and rethrow it.
Stephane Eybert replied on Mon, 2012/12/24 - 6:06pm
This line:
<script src="/socket.io/socket.io.js"></script>
is ambiguous.
It took me a while to understand it referred to the client file:
<script src="http://localhost/programs/socket.io-client/dist/socket.io.js"></script>
and not the server file:
<script src="http://localhost/programs/socket.io/lib/socket.io.js"></script>
Also, it was not clear that the npm socket.io command had to be executed from within the directory containing the server and client files.
After I executed the command:
npm install socket.io
from within the directory containing my server and client files, I could start the server and the client could connect to it.
I had to guess that the line:
require('socket.io');
was in fact looking into the node_modules directory.
It was a painful experience to install this socket.io software, one that makes it not really my friend at the moment.
Stephane Eybert replied on Mon, 2012/12/24 - 6:09pm
Is it that we have to run this npm install socket.io command in every directory that contains a socket.io application ?
Why can't we include socket.io from one single location on the file system ?
Even soft links to my clone copy /home/stephane/programs/socket.io and /home/stephane/programs/socket.io-client would not work.