socket - one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number - Ref. docs.oracle.com
HTTP connections are high latency, it takes time before data comes back from a response. Fast and dynamic apps need to have a low latency. Websockets enable this by establishing a persistent connection between client and server where both parties can send data at any time.
const net = require('net');
const PORT = 8888;
const server = net.createServer((socket) => {
console.log('created server');
socket.on('data', (data) => {
socket.write('pong\n');
});
socket.pipe(connection);
});
server.listen(PORT);
const client = net.createConnection({ port: PORT }, () => {
console.log('created client');
setInterval(() => {
client.write('ping');
}, 1000);
});
client.on('data', (data) => {
console.log('client got data', data.toString());
});
Websockets
A websocket is a persistent socket. Any interchange, from client or server or both, doesnt need to send a packet, the header is 8 bytes unline an ajax call that is 1200, latency is 50-60ms rather than 500ms with ajax. It's a bit more resource intensive when scaling.
The api is similar from client to server. Listen to events by .on
then send with .emit
. A broadcast event doesnt exist on client, or is not necessary. Broadcast sends an event to all.
Socket.io
Example client interacting with socket.io api. Note, this client example is using websockets, not socket.io
const socket = new WebSocket('ws://localhost:8888/socket.io/?EIO=3&transport=websocket');
// Open the socket
socket.onopen = (event) => {
socket.onmessage = (event) => {
console.log(event.data);
};
socket.onclose = (event) => {
console.log(event);
};
};