Junior — Middle
What are the main differences between TCP and UDP protocols in data transmission?
sobes.tech AI
Answer from AI
The main differences between TCP and UDP:
-
TCP (Transmission Control Protocol): connection-oriented, provides reliable data delivery, guarantees order and integrity of packets. Uses acknowledgments (ACK), retransmission of lost packets, and flow control.
-
UDP (User Datagram Protocol): connectionless, does not guarantee delivery, order, or integrity. Faster than TCP, suitable for applications where speed is crucial and data loss is acceptable (e.g., video streaming, gaming).
In the context of Node.js:
- For TCP, the
netmodule is used. - For UDP, the
dgrammodule is used.
Example of creating a UDP socket:
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('message', (msg, rinfo) => {
console.log(`Received: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.bind(41234);
This demonstrates how UDP sockets are created and used in Node.js.