HTML and CSS Reference
In-Depth Information
Echo Server
Let's revisit the echo server example that you completed earlier in the chapter, but this time reimplemented, using
Socket.IO . As you can see in Listing 11-8, the Socket.IO code on the client is strikingly similar to that of your
previous, raw WebSocket example.
Listing 11-8. Socket.IO Client Code
var socket = io.connect('http://0.0.0.0:3000');
socket.on('connect', function() {
messageContainer.innerHTML += "Socket connected to server<br/>";
});
socket.on('message', function (msg) {
messageContainer.innerHTML += "Message received: " + msg +"<br/>";
});
socket.on('disconnect', function() {
messageContainer.innerHTML = "Connection is closed...";
});
var sendSocketMessage = function() {
socket.send("The time is now "+ new Date());
messageContainer.innerHTML += "Sent message.<br/>";
}
Instead of instantiating a WebSocket object directly, you are getting a Socket.IO instance with the io.connect
command. The names of the events that are triggered when a socket is opened or closed have changed to connect and
disconnect . In sendSocketMessage , you send a message on the socket with code that is almost indistinguishable from
that of the earlier WebSocket example.
The full app.js file for setting up an echo server is in Listing 11-9.
Listing 11-9. The Full app.js File
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(3000);
function handler (req, res) {
fs.readFile(__dirname + '/public/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
 
Search WWH ::




Custom Search