Friday, October 16, 2020

WebSocket creating simple client and server


Over the past few years, a new type of communication started to emerge on the web and in mobile apps, called websockets. This protocol has been long-awaited and was finally standardized by the IETF in 2011, paving the way for widespread use.


How do Websockets Work?

At its core, a websocket is just a TCP connection that allows for full-duplex communication, meaning either side of the connection can send data to the other, even at the same time.



To establish this connection, the protocol actually initiates the handshake as a normal HTTP request, but then gets 'upgraded' using the upgrade request HTTP header, like this:


GET /ws/chat HTTP/1.1

Host: chat.example.com

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Key: q1PZLMeDL4EwLkw4GGhADm==

Sec-WebSocket-Protocol: chat, superchat

Sec-WebSocket-Version: 15

Origin: http://example.com



Of the many different websocket libraries for Node.js available to us, I chose to use socket.io throughout this article because it seems to be the most popular and is, in my opinion, the easiest to use. While each library has its own unique API, they also have many similarities since they're all built on top of the same protocol, so hopefully you'll be able to translate the code below to any library you want to use.



Establishing the Connection

In order for a connection to be established between the client and server, the server must do two things:



Hook in to the HTTP server to handle websocket connections

Serve up the socket.io.js client library as a static resource




References:

https://stackabuse.com/node-js-websocket-examples-with-socket-io/

No comments:

Post a Comment