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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
REST API Introduction REST API stands for REpresentational State Transfer API. It is a type of API (Application Programming Interface) that allows communication between different systems over the internet. REST APIs work by sending requests and receiving responses, typically in JSON format, between the client and server.
7 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read