Socket.IO is a library for real-time communication between the server and the client. In Socket.IO, the headers are shared only once and it also works on the top of the TCP layer. Web Sockets are the base of the Socket.IO library. It is easier to implement the Socket.IO in express applications that are not formed with the express-generator.
Socket.IO mainly works on events-based communication. Here the server or the client emits an event and it is caught by another one.
Installation of modules:
Install the Express Generator:
npm install -g express-generator
Create the express application:
npm express applicaion_name
For example, you can create “npm express socketIOTest”
We can also set the view engine while making the express application as:
Setting the view Engine (Optional)
npm express socketIOTest --view=jade
Install the socket IO:
npm install socket.io --save
npm install
Steps to create the socket server:
Go to the App.js file and Import Socket.IO and HTTP module as:
const http=require("http");
const socketio=require("socket.io");
Create a socket IO server:
javascript
const createError = require( 'http-errors' );
const express = require( 'express' );
const path = require( 'path' );
const cookieParser = require( 'cookie-parser' );
const logger = require( 'morgan' );
const http = require( "http" );
const socketio = require( "socket.io" );
const app = express();
const indexRouter = require( './routes/index' );
const usersRouter = require( './routes/users' );
const server = require( 'http' ).createServer(app);
const io = socketio(server);
app.set( 'views' , path.join(__dirname, 'views' ));
app.set( 'view engine' , 'hbs' );
app.use(logger( 'dev' ));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public' )));
app.use( '/' , indexRouter);
app.use( '/users' , usersRouter);
app.use( function (req, res, next) {
next(createError(404));
});
app.use( function (err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get( 'env' )
=== 'development' ? err : {};
res.status(err.status || 500);
res.render( 'error' );
});
module.exports = { app: app, server: server };
|
Now go to the www file inside the BIN folder and replace the code with the following code:
javascript
#!/usr/bin/env node
const app = require( '../app' ).app;
const debug = require( 'debug' )( 'socketiotest:server' );
const http = require( 'http' );
const port = normalizePort(process.env.PORT || '3000' );
app.set( 'port' , port);
const server = require( "../app" ).server;
server.listen(port);
server.on( 'error' , onError);
server.on( 'listening' , onListening);
function normalizePort(val) {
let port = parseInt(val, 10);
if (isNaN(port)) {
return val;
}
if (port >= 0) {
return port;
}
return false ;
}
function onError(error) {
if (error.syscall !== 'listen' ) {
throw error;
}
let bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
switch (error.code) {
case 'EACCES' :
console.error(bind
+ ' requires elevated privileges' );
process.exit(1);
break ;
case 'EADDRINUSE' :
console.error(bind + ' is already in use' );
process.exit(1);
break ;
default :
throw error;
}
}
function onListening() {
let addr = server.address();
let bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug( 'Listening on ' + bind);
}
|
This is how you can link the Socket.IO with the express server.