Gaurav Mehta
Gaurav Mehta

Reputation: 1153

Difference between express and socketio for nodejs

I am new to nodejs programming and going through various js that are being developed for node. My question is a basic one. Can someone please explain me the difference between express and socketio.

From what I know, express is a middleware on which we can use template engines like jade to push data to browser. What does socketio do then? Is it a transport layer? It is confusing to me to understand the difference and why we need express and socket in nodejs apps.

Upvotes: 12

Views: 10662

Answers (3)

Arijit
Arijit

Reputation: 1674

Socket io and express is complete different. But new beginners get confused because in most of the online tutorials people used application server as express and bidirectional communication channel as Socketio. And they put both the code in a same server.js file. Lets take below example (Code copied from a famous online tutorial):

const express = require("express");
const app = express();

const port = 3000;
const http = require('http').createServer();

app.use(require('cors')());
const io = require("socket.io")(http, {
   cors: {
       origin: "*",
       methods: ["GET", "POST"]
   }
})
http.listen(port,()=>{
   console.log("server is running on "+port);
})

After reading this code a new node learner will easily get confused. So It is not required to put both together. for example just remove the express codes from the above code example and still the socketio server will run perfectly.

const port = 3000;
const http = require('http').createServer();

const io = require("socket.io")(http, {
   cors: {
       origin: "*",
       methods: ["GET", "POST"]
   }
})
http.listen(port,()=>{
   console.log("server is running on "+port);
})

I do not use express. I personally like Apache as my application server. So you can use any application server separately which will handle your static requests and work as web server.

Upvotes: 2

Sudhir
Sudhir

Reputation: 99

Express http server gives request response model from client to server.

Socket.io enables bidirectional communication channel between client and server.

Upvotes: 3

Peter Lyons
Peter Lyons

Reputation: 145994

Express is an application server. You define routes and write code to generate your application's pages or API responses. It is basically a port of a ruby project called Sinatra. It works for a traditional request/response HTTP model.

Socket.io is there to help you implement a server push model for real time type features such as alerts/notifications, chat, or whatever updates you want to do if you want them to just show up in the browser without waiting for the user to click a "refresh" button or anything like that.

Upvotes: 17

Related Questions