Differences between socket.io and websockets
Asked Answered
L

12

695

What are the differences between socket.io and websockets in node.js?
Are they both server push technologies? The only differences I felt was,

  1. socket.io allowed me to send/emit messages by specifying an event name.

  2. In the case of socket.io a message from server will reach on all clients, but for the same in websockets I was forced to keep an array of all connections and loop through it to send messages to all clients.

Also, I wonder why web inspectors (like Chrome/firebug/fiddler) are unable to catch these messages (from socket.io/websocket) from server?

Please clarify this.

Lambeth answered 11/4, 2012 at 18:57 Comment(5)
Regarding why web inspectors don't catch the traffic: see How to view WS/WSS Websocket request content using Firebug or other?Bloomer
@Bloomer you don't need Firebug or anything else. Chrome's devtools show WS connections under the networks tab.Prunelle
Check this too (not sure if this is latest) - educba.com/websocket-vs-socket-ioInk
I think the default socket.io behavior (on the server side) is not to send the msg to all clients. Am I wrong? I thought socket.emit(event, data) would send the data to the specific client and not to allCaesura
Any documentation regarding Socket.io vs RSocket please?Hetrick
M
414

Its advantages are that it simplifies the usage of WebSockets as you described in #2, and probably more importantly it provides fail-overs to other protocols in the event that WebSockets are not supported on the browser or server. I would avoid using WebSockets directly unless you are very familiar with what environments they don't work and you are capable of working around those limitations.

This is a good read on both WebSockets and Socket.IO.

http://davidwalsh.name/websocket

Malnutrition answered 11/4, 2012 at 19:24 Comment(11)
Socket.IO is not build on top of WebSockets, it just uses this technology when it is available.Health
Semantic difference and I explained that in the rest of the answer, but I've updated the answer to reflect this.Malnutrition
@moka, from your words can i conclude that the following statement is wrong? Socket.IO is actually more than a layer over WebSockets.Balough
@PulakKantiBhattacharyya could you please specify which statement exactly you are referring to? Socket.IO is way more than just a layer above WebSockets, it has different semantics (marks messages with name), and does failovers to different protocols, as well has heartbeating mechanism. More to that attaches ID's to clients on server side, and more. So it is not just a wrapper, it is full-featured library. In fact it hasn't been supported well in recent years, so I would recommend to use SockJS which is way better and more maintained alternative to Socket.IO.Health
@Health A month ago I would have agreed with you. Socket.io 1.0 is out now and is getting updates.Malnutrition
Must use json web tokens? Socketio auth issues on mobile devices auth0.com/blog/2014/01/15/auth-with-socket-io.Jamisonjammal
See this article and the answer from @rsp. You might not need socket.io anymore nowadays.Hideout
If WebSocket would not be supported on the server, Socket.IO would not be supported also, right? For example on a shared hosting, the reason could be: 1) PHP is available but Node.js is not. 2) only HTTP / HTTPS ports are available and already used by Apache web server. Other reasons?Rightism
@Rightism actually both 1 and 2 are incorrect. You can find php socket libs, and ws is actually an upgraded http req. SocketIO will also fall back to http if websockets are not available. But you wouldn't use socketIO if it wasn't supported of course.Hemocyte
@Hemocyte you still need Node.js to run Socket.IO, so I think it would be problem on a shared hosting.Rightism
Another missing feature for ws while socket.io has is auto-reconnectDartboard
C
841

Misconceptions

There are few common misconceptions regarding WebSocket and Socket.IO:

  1. The first misconception is that using Socket.IO is significantly easier than using WebSocket which doesn't seem to be the case. See examples below.

  2. The second misconception is that WebSocket is not widely supported in the browsers. See below for more info.

  3. The third misconception is that Socket.IO downgrades the connection as a fallback on older browsers. It actually assumes that the browser is old and starts an AJAX connection to the server, that gets later upgraded on browsers supporting WebSocket, after some traffic is exchanged. See below for details.

My experiment

I wrote an npm module to demonstrate the difference between WebSocket and Socket.IO:

It is a simple example of server-side and client-side code - the client connects to the server using either WebSocket or Socket.IO and the server sends three messages in 1s intervals, which are added to the DOM by the client.

Server-side

Compare the server-side example of using WebSocket and Socket.IO to do the same in an Express.js app:

WebSocket Server

WebSocket server example using Express.js:

var path = require('path');
var app = require('express')();
var ws = require('express-ws')(app);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'ws.html'));
});
app.ws('/', (s, req) => {
  console.error('websocket connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.send('message from server', ()=>{}), 1000*t);
});
app.listen(3001, () => console.error('listening on http://localhost:3001/'));
console.error('websocket example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.js

Socket.IO Server

Socket.IO server example using Express.js:

var path = require('path');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'si.html'));
});
io.on('connection', s => {
  console.error('socket.io connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.emit('message', 'message from server'), 1000*t);
});
http.listen(3002, () => console.error('listening on http://localhost:3002/'));
console.error('socket.io example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.js

Client-side

Compare the client-side example of using WebSocket and Socket.IO to do the same in the browser:

WebSocket Client

WebSocket client example using vanilla JavaScript:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening websocket connection');
var s = new WebSocket('ws://'+window.location.host+'/');
s.addEventListener('error', function (m) { log("error"); });
s.addEventListener('open', function (m) { log("websocket connection open"); });
s.addEventListener('message', function (m) { log(m.data); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.html

Socket.IO Client

Socket.IO client example using vanilla JavaScript:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening socket.io connection');
var s = io();
s.on('connect_error', function (m) { log("error"); });
s.on('connect', function (m) { log("socket.io connection open"); });
s.on('message', function (m) { log(m); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.html

Network traffic

To see the difference in network traffic you can run my test. Here are the results that I got:

WebSocket Results

2 requests, 1.50 KB, 0.05 s

From those 2 requests:

  1. HTML page itself
  2. connection upgrade to WebSocket

(The connection upgrade request is visible on the developer tools with a 101 Switching Protocols response.)

Socket.IO Results

6 requests, 181.56 KB, 0.25 s

From those 6 requests:

  1. the HTML page itself
  2. Socket.IO's JavaScript (180 kilobytes)
  3. first long polling AJAX request
  4. second long polling AJAX request
  5. third long polling AJAX request
  6. connection upgrade to WebSocket

Screenshots

WebSocket results that I got on localhost:

WebSocket results - websocket-vs-socket.io module

Socket.IO results that I got on localhost:

Socket.IO results - websocket-vs-socket.io module

Test yourself

Quick start:

# Install:
npm i -g websocket-vs-socket.io
# Run the server:
websocket-vs-socket.io

Open http://localhost:3001/ in your browser, open developer tools with Shift+Ctrl+I, open the Network tab and reload the page with Ctrl+R to see the network traffic for the WebSocket version.

Open http://localhost:3002/ in your browser, open developer tools with Shift+Ctrl+I, open the Network tab and reload the page with Ctrl+R to see the network traffic for the Socket.IO version.

To uninstall:

# Uninstall:
npm rm -g websocket-vs-socket.io

Browser compatibility

As of June 2016 WebSocket works on everything except Opera Mini, including IE higher than 9.

This is the browser compatibility of WebSocket on Can I Use as of June 2016:

enter image description here

See http://caniuse.com/websockets for up-to-date info.

Cambell answered 25/7, 2016 at 1:28 Comment(9)
So basically what you are saying is that, websocket is better than socket.io?Hematuria
@JackMoscovi I wouldn't say that WebSocket is necessarily better. It all depends on the requirements. WebSocket's advantages are that it is a Web standard (first under W3C and whatwg, now under IETF, with an RFC published 5 years ago), it is very lightweight because it is natively supported by the browsers, but the browser support while being good is not universal. Socket.IO supports more browsers and has more functionality, but also comes with some overhead. Sometimes one is better, sometimes the other. It's like choosing between querySelectorAll and jQuery - the answer is not always the sameCambell
Great answer here!! It seems to me socket.io is not longer necessary in many cases... See this great article too! medium.com/@ivanderbyl/…Hideout
This is an awesome test and should be the answer if the question was asked in 2016. Do all socket.io request start with AJAX connection before upgrading to websocket or just at the connection request? I am using socket.io for my browser game and I realize that socket.io comes with some overhead. But I still wonder how much more overhead does socket.io put in every message sent. I can do the test myself but I am not familiar with websocket library. If in general socket.io message has bigger overhead I think I may switch to websocket.Alliterate
@Cambell I don't think these examples are functionally equivalent though? Socket-io handles things like auto-reconnecting when interrupted (which happens on mobile devices) and I think there are security concerns around that which are handled for you? Your plain WS examples, while functionally equivalent, do not have these properties.Lashaunda
Very good comparison. However, it's worth noting that Socket.io adds room name spacing, tons of connection details, lots of logging details, and there are plenty of integration libraries for Socket.IO with Angular, Vue, React and others. Most importantly, you can disable Ajax long-polling and directly connect via WebSocket just like a raw WebSocket connection. In this way, you get everything except the 180kb library as equals. Using WebSocket directly is painful unless you just need the bare minimum. Dropping rooms and access to the community IP is daunting for enterprise.Tammitammie
SocketIO is in fact easier than websockets. OP writes code that exploits some SocketIO's features that he doesn't replicate with Websockets' code, such as rooms and subs. SocketIO offers you a protocol and a subscription service. While Websocket forces you to make your own architecture and protocol. This means that you have to write 10 times more code with Websockets and you have to spend x100 time to design the architecture and debug every mistake you make (trust me, that's why I'm here re-investigating my decisions). SocketIO is not just to support older browsers, it's also easierCorollaceous
Incredible well researched and detailed answer. I wonder to what extent all of this is still accurate 7 years later?Compositor
Well, this is the best answer I've ever seen on StackOverflow ! Not all heroes wear capes ! Thanks for that beautiful explaination !Musket
M
414

Its advantages are that it simplifies the usage of WebSockets as you described in #2, and probably more importantly it provides fail-overs to other protocols in the event that WebSockets are not supported on the browser or server. I would avoid using WebSockets directly unless you are very familiar with what environments they don't work and you are capable of working around those limitations.

This is a good read on both WebSockets and Socket.IO.

http://davidwalsh.name/websocket

Malnutrition answered 11/4, 2012 at 19:24 Comment(11)
Socket.IO is not build on top of WebSockets, it just uses this technology when it is available.Health
Semantic difference and I explained that in the rest of the answer, but I've updated the answer to reflect this.Malnutrition
@moka, from your words can i conclude that the following statement is wrong? Socket.IO is actually more than a layer over WebSockets.Balough
@PulakKantiBhattacharyya could you please specify which statement exactly you are referring to? Socket.IO is way more than just a layer above WebSockets, it has different semantics (marks messages with name), and does failovers to different protocols, as well has heartbeating mechanism. More to that attaches ID's to clients on server side, and more. So it is not just a wrapper, it is full-featured library. In fact it hasn't been supported well in recent years, so I would recommend to use SockJS which is way better and more maintained alternative to Socket.IO.Health
@Health A month ago I would have agreed with you. Socket.io 1.0 is out now and is getting updates.Malnutrition
Must use json web tokens? Socketio auth issues on mobile devices auth0.com/blog/2014/01/15/auth-with-socket-io.Jamisonjammal
See this article and the answer from @rsp. You might not need socket.io anymore nowadays.Hideout
If WebSocket would not be supported on the server, Socket.IO would not be supported also, right? For example on a shared hosting, the reason could be: 1) PHP is available but Node.js is not. 2) only HTTP / HTTPS ports are available and already used by Apache web server. Other reasons?Rightism
@Rightism actually both 1 and 2 are incorrect. You can find php socket libs, and ws is actually an upgraded http req. SocketIO will also fall back to http if websockets are not available. But you wouldn't use socketIO if it wasn't supported of course.Hemocyte
@Hemocyte you still need Node.js to run Socket.IO, so I think it would be problem on a shared hosting.Rightism
Another missing feature for ws while socket.io has is auto-reconnectDartboard
C
113

tl;dr;

Comparing them is like comparing Restaurant food (maybe expensive sometimes, and maybe not 100% you want it) with homemade food, where you have to gather and grow each one of the ingredients on your own.

Maybe if you just want to eat an apple, the latter is better. But if you want something complicated and you're alone, it's really not worth cooking and making all the ingredients by yourself.


I've worked with both of these. Here is my experience.

SocketIO

  • Has autoconnect

  • Has namespaces

  • Has rooms

  • Has subscriptions service

  • Has a pre-designed protocol of communication

    (talking about the protocol to subscribe, unsubscribe or send a message to a specific room, you must all design them yourself in websockets)

  • Has good logging support

  • Has integration with services such as redis

  • Has fallback in case WS is not supported (well, it's more and more rare circumstance though)

  • It's a library. Which means, it's actually helping your cause in every way. Websockets is a protocol, not a library, which SocketIO uses anyway.

  • The whole architecture is supported and designed by someone who is not you, thus you dont have to spend time designing and implementing anything from the above, but you can go straight to coding business rules.

  • Has a community because it's a library (you can't have a community for HTTP or Websockets :P They're just standards/protocols)

Websockets

  • You have the absolute control, depending on who you are, this can be very good or very bad
  • It's as light as it gets (remember, its a protocol, not a library)
  • You design your own architecture & protocol
  • Has no autoconnect, you implement it yourself if yo want it
  • Has no subscription service, you design it
  • Has no logging, you implement it
  • Has no fallback support
  • Has no rooms, or namespaces. If you want such concepts, you implement them yourself
  • Has no support for anything, you will be the one who implements everything
  • You first have to focus on the technical parts and designing everything that comes and goes from and to your Websockets
  • You have to debug your designs first, and this is going to take you a long time

Obviously, you can see I'm biased to SocketIO. I would love to say so, but I'm really really not.

I'm really battling not to use SocketIO. I dont wanna use it. I like designing my own stuff and solving my own problems myself.

But if you want to have a business and not just a 1000 lines project, and you're going to choose Websockets, you're going to have to implement every single thing yourself. You have to debug everything. You have to make your own subscription service. Your own protocol. Your own everything. And you have to make sure everything is quite sophisticated. And you'll make A LOT of mistakes along the way. You'll spend tons of time designing and debugging everything. I did and still do. I'm using websockets and the reason I'm here is because they're unbearable for a one guy trying to deal with solving business rules for his startup and instead dealing with Websocket designing jargon.

Choosing Websockets for a big application ain't an easy option if you're a one guy army or a small team trying to implement complex features. I've wrote more code in Websockets than I ever wrote with SocketIO in the past, for ten times simpler things than I did with SocketIO.

All I have to say is ... Choose SocketIO if you want a finished product and design. (unless you want something very simple in functionality)

Corollaceous answered 11/7, 2020 at 10:38 Comment(0)
S
46

Im going to provide an argument against using socket.io.

I think using socket.io solely because it has fallbacks isnt a good idea. Let IE8 RIP.

In the past there have been many cases where new versions of NodeJS has broken socket.io. You can check these lists for examples... https://github.com/socketio/socket.io/issues?q=install+error

If you go to develop an Android app or something that needs to work with your existing app, you would probably be okay working with WS right away, socket.io might give you some trouble there...

Plus the WS module for Node.JS is amazingly simple to use.

Shaeffer answered 19/12, 2015 at 19:33 Comment(0)
A
40

Using Socket.IO is basically like using jQuery - you want to support older browsers, you need to write less code and the library will provide with fallbacks. Socket.io uses the websockets technology if available, and if not, checks the best communication type available and uses it.

Amanita answered 21/12, 2016 at 6:32 Comment(2)
As far as I'm aware, I think this is a little bit bad example as jQuery is not to support older browsers. This gives newbies the impression that nowadays jQuery is supposed to be used. There is babel for this in case you use latest ECMAs. :D Excuse my nitpicking, I just see newbies using jQuery for no good reason all the time, as they learn jquery before javascript, and I just wanna contribute in reducing this bad practice phenomenon.Corollaceous
Well supporting the browser inconsistencies was the initial purpose of jQuery. If you look at the date on my answer, you'll get it. It didn't age well ofcourse, because now browser inconsistencies are non-existent.Amanita
S
24

https://socket.io/docs/#What-Socket-IO-is-not (with my emphasis)

What Socket.IO is not

Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the packet id when a message acknowledgement is needed. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server either. Please see the protocol specification here.

// WARNING: the client will NOT be able to connect!
const client = io('ws://echo.websocket.org');
Sauer answered 10/3, 2020 at 21:37 Comment(0)
D
9

I would like provide one more answer in 2021. socket.io has become actively maintained again since 2020 Sept. During 2019 to 2020 Aug(almost 2 years) there was basically no activity at all and I had thought the project may be dead.

Socket.io also published an article called Why Socket.IO in 2020?, except for a fallback to HTTP long-polling, I think these 2 features are what socket.io provides and websocket lacks of

  • auto-reconnection
  • a way to broadcast data to a given set of clients (rooms/namespace)

One more feature I find socket.io convenient is for ws server development, especially I use docker for my server deployment. Because I always start more than 1 server instances, cross ws server communication is a must and socket.io provide https://socket.io/docs/v4/redis-adapter/ for it.

With redis-adapter, scaling server process to multiple nodes is easy while load balance for ws server is hard. Check here https://socket.io/docs/v4/using-multiple-nodes/ for further information.

Dartboard answered 28/9, 2021 at 9:22 Comment(0)
J
8

Even if modern browsers support WebSockets now, I think there is no need to throw SocketIO away and it still has its place in any nowadays project. It's easy to understand, and personally, I learned how WebSockets work thanks to SocketIO.

As said in this topic, there's a plenty of integration libraries for Angular, React, etc. and definition types for TypeScript and other programming languages.

The other point I would add to the differences between Socket.io and WebSockets is that clustering with Socket.io is not a big deal. Socket.io offers Adapters that can be used to link it with Redis to enhance scalability. You have ioredis and socket.io-redis for example.

Yes I know, SocketCluster exists, but that's off-topic.

Jethro answered 20/3, 2019 at 15:53 Comment(0)
J
4

Socket.IO uses WebSocket and when WebSocket is not available uses fallback algo to make real time connections.

Joerg answered 17/8, 2017 at 7:39 Comment(0)
M
1

TLDR:

'Socket.io' is an application layer specification that can be implemented on top of/using the application layer specification 'websockets'.

websocket spec
socket.io spec

I think the simple answer here is in basic web technology definitions:

  1. Specification: A documented standard detailing the requirements for a program to achieve in order to be labeled as "an implementation of some sepc." It is important to achieve this rubber stamp when building programs, because any program is only as good at the machine executing the code. Programming is fundamentally built upon specifications, and if, they are not followed code will not execute correctly. However, a specification does nothing. It is just a text document.
  2. Implementation: This is actual, executable code that accomplishes what the specification says to do.
  3. Application Layer - System that defines messages and handshakes sent over transport. This is the stuff you have to know when working with HTTP/Websockets/Socketio. It defines how the connections will be made, authenticated, data will be sent, and how it will arrive.
Mesognathous answered 28/7, 2022 at 17:22 Comment(0)
A
1

TL/DR

While socket.io is a library that makes life easier for us developers, WebSocket is just a protocol which you can use by itself, or can be used thru socket.io (which is essentially acting as a layer above Websockets).

Socket.io also comes with a lot of handy features, like falling back to HTTP Polling on browsers which don't support the WebSocket protocol, which can be useful for some applications.

Though I would say with my experience with both of these technologies, socket.io isn't very useful anymore as most modern browsers already natively support the Websocket protocol, and socket.io is adding a layer of bloat and tends to cause issues when scaling your application.

Websockets

WebSocket is a protocol that enables two-way realtime communication between client and server. It allows for bi-directional, full-duplex communication over a persistent, single-socket connection.

Socket.io

On the other hand, Socket.IO is a library that provides an abstraction layer on top of WebSockets, making it easier to create realtime applications. It provides additional capabilities such as automatic reconnections, broadcast support, or falling back to HTTP long polling (for legacy browsers which don't support the WebSocket protocol).

Airtoair answered 31/5, 2023 at 22:59 Comment(0)
L
1

In almost all cases you want to use socket.io unless you have a very trivial messaging case.

If you want to use ws directly, here is a gist to get you started since a minimal example is missing in the documentation.

Lied answered 3/9, 2023 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.