Integration of WebSocket in nodejs application
The reactive aspect of nodejs applications is synonymous with the nodejs runtime itself. However, the real-time magic is attributed to the WebSocket addition. This article introduces how to integrate WebSocket support within an existing nodejs application.
In this article we will talk about:
- WebSocket support with or without
socket.io - WebSocket support with or without
expressjs - Modularizations of WebSocket
Even though this blog post was designed to offer complementary materials to those who bought my Testing
nodejsApplications book, the content can help any software developer to tuneup working environment. You use this link to buy the book.
Show me the code
Express routes use socket.io instance to deliver messages of a socket/socket.io enabled application looks like following:
//module/socket.js - server or express app instance
module.exports = function(server){
var io = socket();
io = io.listen(server);
io.on('connect', fn);
io.on('disconnect',fn);
};
//OR
//module/socket.js
var io = require('socket.io');
module.exports = function(server){
//server will be provided by the calling application
//server = require('http').createServer(app);
io = io.listen(server);
return io;
};
//module/routes.js - has all routes initializations
var route = require('express').Router();
module.exports = function(){
route.all('',function(req, res, next){
res.send();
next();
});
};
//in server.js
var app = require('express').express(),
server = require('http').createServer(app),
sio = require('module/socket.js')(server);
//@link http://stackoverflow.com/a/25618636/132610
//Sharing session data between SocketIO and Express
sio.use(function(socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
//application app.js|server.js initialization, etc.
require('module/routes')(server); ;
What can possibly go wrong?
When working in this kind of environment, we will find these two points to be of interest, if not challenging:
- For
socket.ioapplication to use sameexpressjsserver instance, or sharing route instance withsocket.ioserver - Sharing session between
socket.ioandexpressjsapplication
Conclusion
In this article, we revisited how to add real-time experience to a nodejs application. The use of WebSocket and Pub/Sub powered by a key/value data store was especially the main focus of this article. There are additional complimentary materials in the “Testing nodejs applications” book.
References
- Testing
nodejsApplications book socket.iowithin concurrent processes ~ Tolleiv Nietsch Blognodejs,expressjsandsocket.ioapplication ~ DevelopIQ Blog- Modularize Your Chat App(or How to Write a
nodejsExpress App in More Than One File) ~ Philosophie Is Thinking Medium Bacon.js+nodejs+MongoDB: Functional Reactive Programming on the Server ~ Carbon Five Blog- Modularizing
socket.iowith express 4 ~ StackOverflow Answer
