Junior
What do you know about network protocols?
sobes.tech AI
Answer from AI
Network protocols are a set of rules and agreements that define data formats and principles of interaction between devices in a network. They ensure reliability, routing, and integrity of data transmission.
The most important protocols for Node.js:
- HTTP/1.1, HTTP/2, HTTP/3: The foundation of web communications. Node.js has built-in modules for working with HTTP.
- TCP (Transmission Control Protocol): A reliable, connection-oriented transport layer protocol. Guarantees delivery of data packets and their order.
- UDP (User Datagram Protocol): A connectionless, unreliable transport layer protocol. Faster than TCP, suitable for streaming data and time-sensitive applications.
- TLS/SSL: Protocols for ensuring security and data encryption in networks, often used over TCP for HTTPS.
Examples of usage in Node.js:
// Creating a simple HTTP server
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, world!\n');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
// Example TCP server
const net = require('net');
const server = net.createServer((socket) => {
socket.on('data', (data) => {
console.log('Data received:', data.toString());
socket.write('Data received\n');
});
socket.on('end', () => {
console.log('Client disconnected');
});
});
server.listen(4000, '127.0.0.1', () => {
console.log('TCP server running on 127.0.0.1:4000');
});
Understanding network protocols is critical for developing scalable and reliable network applications in Node.js.