Real life, a socket is
An entry point for a power cable.
A software socket is also an entry point that accepts a network connection from another computer.
Sockets play a key role in keeping connections between computers neat and tidy.
Technologies make sockets possible: IP addresses, ports and TCP/IP (Transmission Control Protocol/Internet Protocol).
192.168.68.1
which is a unique number identifies your computer when its connected to a network using the Internet Protocol (IP).
192.168.68.1:3000
.
Simple sense: socket = IP address + port → for sending / receiving information over the internet (two-way communication) + kept organized by TCP.
The bidirectional channel between server and client via WebSocket connection / HTTP long-polling.
2 layers: the low-level plumbing (engine.io) and the high-level API (socket.io). Read more in the doc.
Namespaces: allows you to split the logic of your application over a single shared connection (also “multiplexing”)
Client side events: “connect”, “disconnect”, “reconnect”, … (eg. io.on(”connect”)
) + other events.
Service side events: “connection”, “disconnect”, “disconnecting”
Some codes
// client
socket.emit("hello", "world", (response) => {
console.log(response); // "got it"
});
// server
io.on("connection", (socket) => {
socket.on("hello", (arg, callback) => {
console.log(arg); // "world"
callback("got it");
});
});
Get the id of a socket on client
const socket = io(`${this._bot.endPointBack}/streaming-response`, {
query: { botId: this._bot.id, sourceNode, channel },
transports: ['websocket']
});
socket.on('connect', () => {
console.log('Connected with socket ID:', this.socket.id);
});
If you use NestJS, socket/websocket are supported out-of-the-box (you don’t need to install package socket.io)