Home > Back-end >  WebSocket server tied to the HTTP server but why?
WebSocket server tied to the HTTP server but why?

Time:06-27

I found a lot of examples that shows how to create a websocket server (nodejs).

Example for illustration (on my side I am using expressJS):

var http = require('http'); /** QUESTION 2 (optional) */
var WebSocketServer = require('websocket').server;


var httpServer = http.createServer((request, response) => {
  ...
});
httpServer.listen(8080, () => {
  ...
});

wsServer = new WebSocketServer({
    httpServer: server, /** QUESTION 1 */
    ...
});

QUESTION 1: Why does the WebSocketServer needs the httpServer instance ? I would imagined creating a WS Server specifying a host and port only, not a HTTP instance.

QUESTION 2: Can I use ExpressJS ?

CodePudding user response:

Finally got it !

So HTTP and WebSockets are both protocols. WebSockets uses HTTP protocol to work. So answering my own QUESTION 1: WebSockets increases the HTTP protocol by knowing how to communicate with websocket protocol. This is why a HTTP server is needed.

For question 2, it's a bit more subtile. You can use two differents HTTP instance (one for a normal HTTP API and another one for the WebSockets). Then it brings the question of: Why do you need both ? And the answer is pretty logical. Well if you already have a HTTP instance (http.createServer or Express appServer), then you can re-use the same HTTP instance to avoid being greedy on your server resources.

So basically, to use the same HTTP instance in Express and with websocket.io (as an illustration). You would do

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");

/** socket.io is using the single 'server' instance (bound to it) */
const io = new Server(server);

/** Add a route to express that is bound to the single HTTP server instance */
app.get('/', (req, res) => {
  res.sendFile(__dirname   '/index.html');
});

/** Add a websocket path that is bound to the single HTTP server instance */
io.on('connection', (socket) => {
  console.log('a user connected');
});

/** Express is using the single 'server' instance (bound to it). */
server.listen(3000, () => {
  console.log('listening on *:3000');
});

Source: https://socket.io/fr/get-started/chat

In that example we can see that expressJS and websocket.io are using the same HTTP instance ! \o/

CodePudding user response:

A WebSocket is a special streaming mode of an HTTP connection. The user connects to an HTTP server and then request that server to switch to the WebSocket method.

This was before HTTP2 and HTTP3 which offer similar capabilities without the need to switch to another mode. At the same time, the WebSocket allows you to define the format of the data being shared. In most cases, though, it's going to be JSON so it HTTP2/3 would work the same way.

  • Related