TIL Websockets
POSTED ON:
TAGS: node communication
Today I learned about WebSockets!
Using WebSockets in Node.js #
WebSockets are an alternative to HTTP communication in Web Applications.
-
WebSockets are great for real-time and long-lived communications.
-
HTTP is great for occasional data exchange and interactions initiated by the client.
-
HTTP is much simpler to implement, while WebSockets require a bit more overhead.
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: node