Creating Socket.IO Server using Express Generator
Last Updated :
14 Apr, 2023
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');
// Create the http server
const server = require('http').createServer(app);
// Create the Socket IO server on
// the top of http server
const io = socketio(server);
// View engine setup
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);
// Catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// Error handler
app.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:
javascript
#!/usr/bin/env node
// Module dependencies
const app = require('../app').app;
const debug = require('debug')('socketiotest:server');
const http = require('http');
// Get port from environment and store in Express
const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
// Create HTTP server
const 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) {
let 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" event
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
let 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() {
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.
Similar Reads
How to use TypeScript to build Node.js API with Express ? TypeScript is a powerful version of JavaScript that incorporates static typing and other features, making it easy to build and maintain large applications. Combined with Node.js and Express, TypeScript can enhance your development experience by providing better type safety and tools. This guide will
4 min read
Requesting in http vs Requesting in Express.js Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that Node.js is not a framework and itâs not a programming language. Most people are confused and understand itâs a framework or a programming language. We
3 min read
How to Configure Socket.IO with Demo-Chat App in Node.js ? For making a chat app, it is required that the server sends data to the client but the client should also respond back to the server. This can be done by making use of the Websockets. A WebSocket is a kind of communication pipe opened in two directions. Prerequisite: Node.js: It is an open source Ja
5 min read
Node vs Express Node.js and Express are two essential tools in the JavaScript ecosystem, especially for server-side development. While they are often used together, they serve different purposes. This article will explain what Node.js and Express are, their key differences, and when to use each.Table of Content Nod
5 min read
How to deploy Node.js app on Heroku from GitHub ? In this article, we will be looking at how to deploy your Demo Node.js app to Heroku. At the end of this article, we will have a basic Hello World app running on a public domain that can be accessed by anyone. The Node must be installed on your machine. Refer to this article How to install Node on y
3 min read
What is Express Generator ? Express Generator is a Node.js Framework like ExpressJS which is used to create express Applications easily and quickly. It acts as a tool for generating express applications. In this article, we will discuss the Express Generator.Express GeneratorExpress Generator is a command-line tool for quickly
3 min read