Creating Socket.IO Server using Express Generator - GeeksforGeeks

12 Jun, 2020
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 the express applications that are not formed with express-generator.
Socket.IO mainly works on events based communication. Here the server or the client emits an event and it is being caught by another one.
Installation of modules:
Install the Express Generator:npm install -g express-generatorCreate the express application:npm express applicaion_nameFor 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=jadeInstall the socket IO:npm install socket.io --save
npm install
Install the Express Generator:npm install -g express-generator
Install the Express Generator:
npm install -g express-generator
Create the express application:npm express applicaion_nameFor example you can create “npm express socketIOTest”
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
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
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:var http=require("http");
var socketio=require("socket.io");
Create a socket IO server:var createError = require('http-errors');var express = require('express');var path = require('path');var cookieParser = require('cookie-parser');var logger = require('morgan');var http = require("http");var socketio = require("socket.io");var app = express();  var indexRouter = require('./routes/index');var usersRouter = require('./routes/users');  // Create the http serverconst server = require('http').createServer(app);  // Create the Socket IO server on // the top of http serverconst io = socketio(server);  // View engine setupapp.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);  // Catch 404 and forward to error handlerapp.use(function (req, res, next) {    next(createError(404));});  // Error handlerapp.use(function (err, req, res, next) {      // Set locals, only providing error    // in development    res.locals.message = err.message;    res.locals.error = req.app.get('env')             === 'development' ? err : {};      // render the error page    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:#!/usr/bin/env node  // Module dependenciesvar app = require('../app').app;var debug = require('debug')('socketiotest:server');var http = require('http');  // Get port from environment and store in Expressvar port = normalizePort(process.env.PORT || '3000');app.set('port', port);  // Create HTTP servervar server = require("../app").server;  // Listen on provided port, on all// network interfaces.  server.listen(port);server.on('error', onError);server.on('listening', onListening);  // Normalize a port into a number,// string, or false.function normalizePort(val) {    var port = parseInt(val, 10);      if (isNaN(port)) {          // Named pipe        return val;    }      if (port >= 0) {          // Port number        return port;    }      return false;}  // Event listener for HTTP server "error" eventfunction onError(error) {    if (error.syscall !== 'listen') {        throw error;    }      var bind = typeof port === 'string'        ? 'Pipe ' + port        : 'Port ' + port;      // Handle specific listen errors with    // friendly messages    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;    }}  // Event listener for HTTP server "listening" event.function onListening() {    var addr = server.address();    var bind = typeof addr === 'string'        ? 'pipe ' + addr        : 'port ' + addr.port;    debug('Listening on ' + bind);}
Go to the App.js file and Import Socket.IO and http module as:var http=require("http");
var socketio=require("socket.io");

var http=require("http");
var socketio=require("socket.io");

Create a socket IO server:var createError = require('http-errors');var express = require('express');var path = require('path');var cookieParser = require('cookie-parser');var logger = require('morgan');var http = require("http");var socketio = require("socket.io");var app = express();  var indexRouter = require('./routes/index');var usersRouter = require('./routes/users');  // Create the http serverconst server = require('http').createServer(app);  // Create the Socket IO server on // the top of http serverconst io = socketio(server);  // View engine setupapp.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);  // Catch 404 and forward to error handlerapp.use(function (req, res, next) {    next(createError(404));});  // Error handlerapp.use(function (err, req, res, next) {      // Set locals, only providing error    // in development    res.locals.message = err.message;    res.locals.error = req.app.get('env')             === 'development' ? err : {};      // render the error page    res.status(err.status || 500);    res.render('error');});  module.exports = { app: app, server: server };
var createError = require('http-errors');var express = require('express');var path = require('path');var cookieParser = require('cookie-parser');var logger = require('morgan');var http = require("http");var socketio = require("socket.io");var app = express();  var indexRouter = require('./routes/index');var usersRouter = require('./routes/users');  // Create the http serverconst server = require('http').createServer(app);  // Create the Socket IO server on // the top of http serverconst io = socketio(server);  // View engine setupapp.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);  // Catch 404 and forward to error handlerapp.use(function (req, res, next) {    next(createError(404));});  // Error handlerapp.use(function (err, req, res, next) {      // Set locals, only providing error    // in development    res.locals.message = err.message;    res.locals.error = req.app.get('env')             === 'development' ? err : {};      // render the error page    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:#!/usr/bin/env node  // Module dependenciesvar app = require('../app').app;var debug = require('debug')('socketiotest:server');var http = require('http');  // Get port from environment and store in Expressvar port = normalizePort(process.env.PORT || '3000');app.set('port', port);  // Create HTTP servervar server = require("../app").server;  // Listen on provided port, on all// network interfaces.  server.listen(port);server.on('error', onError);server.on('listening', onListening);  // Normalize a port into a number,// string, or false.function normalizePort(val) {    var port = parseInt(val, 10);      if (isNaN(port)) {          // Named pipe        return val;    }      if (port >= 0) {          // Port number        return port;    }      return false;}  // Event listener for HTTP server "error" eventfunction onError(error) {    if (error.syscall !== 'listen') {        throw error;    }      var bind = typeof port === 'string'        ? 'Pipe ' + port        : 'Port ' + port;      // Handle specific listen errors with    // friendly messages    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;    }}  // Event listener for HTTP server "listening" event.function onListening() {    var addr = server.address();    var bind = typeof addr === 'string'        ? 'pipe ' + addr        : 'port ' + addr.port;    debug('Listening on ' + bind);}
#!/usr/bin/env node  // Module dependenciesvar app = require('../app').app;var debug = require('debug')('socketiotest:server');var http = require('http');  // Get port from environment and store in Expressvar port = normalizePort(process.env.PORT || '3000');app.set('port', port);  // Create HTTP servervar server = require("../app").server;  // Listen on provided port, on all// network interfaces.  server.listen(port);server.on('error', onError);server.on('listening', onListening);  // Normalize a port into a number,// string, or false.function normalizePort(val) {    var port = parseInt(val, 10);      if (isNaN(port)) {          // Named pipe        return val;    }      if (port >= 0) {          // Port number        return port;    }      return false;}  // Event listener for HTTP server "error" eventfunction onError(error) {    if (error.syscall !== 'listen') {        throw error;    }      var bind = typeof port === 'string'        ? 'Pipe ' + port        : 'Port ' + port;      // Handle specific listen errors with    // friendly messages    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;    }}  // Event listener for HTTP server "listening" event.function onListening() {    var addr = server.address();    var 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.
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
Express.js express.Router() Function
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript