# WebSocket API and SocketIO ### I. WebSocket API > WebSocket is a computer communications protocol, providing full-duplex communications channels over a single TCP connection. > *-Wikipedia* According to the definition, this connection is similar to how the phone line works where both parties would send messages or talk at the same time and that is what WebSocket API do. It opens a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply or refresh serveral times to see any updates because the connection is open infinitely until 1 side of connection disconnect. To be able to make use of WebSocket, we need to: - create a WebSocket server on the server side, which is nothing more than an application listening on any port of a TCP server that follows a specific protocol. - instantiate WebSocket object that point to the server to send and receive data on the connection. As you can see, the `ws` before our server url is the protocol to create handshake between client and server. ```javascript= // Create WebSocket connection. const socket = new WebSocket('ws://localhost:8080'); // Connection opened socket.addEventListener('open', function (event) { socket.send('Hello Server!'); }); // Listen for messages socket.addEventListener('message', function (event) { console.log('Message from server ', event.data); }); // src: https://developer.mozilla.org/ ``` ### II. SocketIO #### 1) What is it SocketIO is a library that enables low-latency, bidirectional and event-based communication between a client and a server. It utilizes WebSocket and add some other features, like: - initial setup for WebSocket server. - allow connection to be established in the presence of proxies and load balancers. - allow broadcasting. #### 2) Usage Here's an example of using SocketIO to send message to send message from different clients. You can use below command to install SocketIO. For <u>server</u>: ``` npm install socket.io ``` For <u>client</u>: ``` npm install socket.io-client ``` Because Socket IO enable event-based communication, there are several events that we would use to create the connection between client and server. - Emitting events: https://socket.io/docs/v4/emitting-events/ - Listening to events: https://socket.io/docs/v4/listening-to-events/ - Broadcasting events: https://socket.io/docs/v4/listening-to-events/ **On the server side:** ```javascript= const http = require('http').createServer(); const fs = require('fs'); const io = require('socket.io')(http); io.on('connection', (socket) => { socket.on('message', (message) => { io.emit('message', message); }); }); http.listen(8080, () => console.log('listening on http://localhost:8080')); ``` First create an http server and then import socket io, and we can use events provided by the library to describe how we handle an action. So here, i have the `connection` event which is fired upon a new connection, and the argument is a socket instance. `connection` is a reserved action, so for other custom actions, you should choose a different name. When there's a connection, we defined an action that handle the message from client, i call it the message action, this action takes the message from client side and emit it back to all clients that are connected to this server. **On the client side:** ```javascript= const socket = io('ws://localhost:8080'); socket.on('message', text => { const el = document.createElement('li'); el.innerHTML = text; document.querySelector('ul').appendChild(el); }); document.querySelector("input[type='text']").onkeydown = (e) => { if (e.key !== 'Enter') { return } const text = document.querySelector('input').value; socket.emit('message', text) document.querySelector('input').value = ''; } ``` Now, take a look at the client side. Here, i have a simple input to send message. Then i create the socket that connects to the server. When i input and enter, i send this text to the server under "message" action, ther server received the text and emit to all client connecting to it. On all the clients, they get the message from server and display it. ![](https://i.imgur.com/Nu6EedA.png) Testing 2 clients connected to the same server, both client will receive the messsages as above image. **Notice** : - if 1 client is offline, that client will not able to see old messages, you should save the messages in the database or other memory that suits your case. - you can also send binary files, not just string. ### III. Conclusion If you want to make something for streaming videos, images, WebRTC is other thing that you can look into. WebTransport is in development and is expected to replace current WebSocket but it will not be available anytime soon. There're other libraries that help create socket easily, like Firebase, Apollo, Pusher,... but SocketIO is one of the most popular and simple one to use. <small> Published date: 2022-04-19 <br/> Also published <a href="https://medium.com/goalist-blog/websocket-api-and-socketio-923a836cb914">here</a>. </small>