Today I Learned - Rocky Kev

TIL Websockets

POSTED ON:

TAGS:

Today I learned about WebSockets!

Using WebSockets in Node.js

WebSockets are an alternative to HTTP communication in Web Applications.

They offer a long lived, bidirectional communication channel between client and server.

Once established, the channel is kept open, offering a very fast connection with low latency and overhead.

// The server
// 1 - establishes a new server with port 8080
// 2 - connects
// 3 - adds events
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
console.log('New WebSocket connection');

ws.on('message', (message) => {
console.log(`Received message: ${message}`);
ws.send(`You said: ${message}`);
});
});



// The Client
// 1 - Starts listening on ws://localhost:8080.
// 2 - When the connection is established, the open event triggers and the client sends a message to the server using the send() method.
// 3 - The client then listens for incoming messages using the message event, and logs any incoming messages to the console.

const socket = new WebSocket('ws://localhost:8080');

socket.addEventListener('open', () => {
console.log('Connected to WebSocket server');
socket.send('Hello from the client!');
});

socket.addEventListener('message', (event) => {
console.log(`Received message: ${event.data}`);
});

Secured WebSockets

Always use the secure, encrypted protocol for WebSockets, wss://.
ws:// refers to the unsafe WebSockets version (the http:// of WebSockets), and should be avoided for obvious reasons.

via How to Use WebSockets with Node.js

https://github.com/websockets/ws

https://www.npmjs.com/package/ws


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL keywords in package.json

Today I learned what keywords are in a package.json file! It's a collection of keywords about a module. Keywords can help identify a package, related modules and software, and concepts.

TIL functional async/await

PLACEHOLDER