Socket.io: Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server.
There are several Socket.IO server implementations available:
Here's a basic example with plain WebSockets:
Server (based on ws) code:
import { WebSocketServer } from "ws";
const server = new WebSocketServer({ port: 3000 });
server.on("connection", (socket) => {
// send a message to the client
socket.send(JSON.stringify({
type: "hello from server",
content: [ 1, "2" ]
}));
// receive a message from the client
socket.on("message", (data) => {
const packet = JSON.parse(data);
switch (packet.type) {
case "hello from client":
// ...
break;
}
});
});
Client-side code:
const socket = new WebSocket("ws://localhost:3000");
socket.addEventListener("open", () => {
// send a message to the server
socket.send(JSON.stringify({
type: "hello from client",
content: [ 3, "4" ]
}));
});
// receive a message from the server
socket.addEventListener("message", ({ data }) => {
const packet = JSON.parse(data);
switch (packet.type) {
case "hello from server":
// ...
break;
}
});
Here's the same example with Socket.IO:
server-side code:
import { Server } from "socket.io";
const io = new Server(3000);
io.on("connection", (socket) => {
// send a message to the client
socket.emit("hello from server", 1, "2", { 3: Buffer.from([4]) });
// receive a message from the client
socket.on("hello from client", (...args) => {
// ...
});
});
Client:
import { io } from "socket.io-client";
const socket = io("ws://localhost:3000");
// send a message to the server
socket.emit("hello from client", 5, "6", { 7: Uint8Array.from([8]) });
// receive a message from the server
socket.on("hello from server", (...args) => {
// ...
});
Socket.IO provides a convenient way to send an event and receive a response:
Sender
socket.emit("hello", "world", (response) => {
console.log(response); // "got it"
});
Receiver:
socket.on("hello", (arg, callback) => {
console.log(arg); // "world"
callback("got it");
});
You can also add a timeout:
socket.timeout(5000).emit("hello", "world", (err, response) => {
if (err) {
// the other side did not acknowledge the event in the given delay
} else {
console.log(response); // "got it"
}
});
Broadcasting:
io.emit("hello");
// to all connected clients in the "news" room
io.to("news").emit("hello");
Multiplexing: Namespaces allow you to split the logic of your application over a single shared connection. This can be useful for example if you want to create an "admin" channel that only authorized users can join.
// classic users
});
io.of("/admin").on("connection", (socket) => {
// admin users
});
Comments
Post a Comment