Server ma’lumotnomasi
Server obyekti
Node.js-dagi server obyektlari tarmoq serverlarini yaratish uchun ishlatiladi. Turli xil modullar o‘zlarining Server dasturlarini taqdim etadilar:
http.Server- HTTP serverlarini yaratish uchunhttps.Server- HTTPS serverlarini yaratish uchunnet.Server- TCP serverlarini yaratish uchuntls.Server- TLS/SSL serverlarini yaratish uchun
Ushbu server obyektlari mijoz ulanishlarini boshqaradi, so‘rovlarni qayta ishlaydi va tegishli protokollariga mos keladigan javoblarni yetkazib beradi.
Umumiy server usullari
| Metod | Tavsif |
|---|---|
| server.listen([port][, host][, backlog][, callback]) | Server ulanishlarni tinglashni boshlaydi. Callback server bog‘langandan so‘ng amalga oshiriladi. |
| server.close([callback]) | Serverning yangi ulanishlarni qabul qilishini to‘xtatadi. Callback barcha ulanishlar yopilganda chaqiriladi. |
| server.address() | Bog‘langan manzilni, manzil familiyasini va server portini qaytaradi. |
| server.getConnections(callback) | Asinxron ravishda serverdagi bir vaqtda ulanishlar sonini oladi. |
Umumiy server hodisalari
| Event | Tavsif |
|---|---|
| 'close' | Server yopilganda ishga tushadi. |
| 'connection' | Yangi ulanish o‘rnatilganda ishga tushadi. |
| 'error' | Xato yuz berganda ishga tushadi. |
| 'listening' | server.listen() chaqirilgandan so‘ng server bog‘langanda (bound) ishga tushadi. |
HTTP serveri
Node.js’dagi HTTP server http.createServer() usuli yordamida yaratilgan:
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// Handle requests
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
// Start the server
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
// Handle server events
server.on('error', (err) => {
console.error(`Server error: ${err.message}`);
});
server.on('close', () => {
console.log('Server closed');
});
Misolni ishga tushirish »
HTTPS serveri
HTTPS serveri SSL sertifikatlarini talab qiladi va https.createServer() usuli yordamida yaratilgan:
const https = require('https');
const fs = require('fs');
// SSL options - in a production environment, use properly signed certificates
const options = {
key: fs.readFileSync('server-key.pem'), // Path to your key file
cert: fs.readFileSync('server-cert.pem') // Path to your certificate file
};
// Create an HTTPS server
const server = https.createServer(options, (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Secure World\n');
});
// Start the server
const PORT = 3443;
server.listen(PORT, () => {
console.log(`Server running at https://localhost:${PORT}/`);
});
Misolni ishga tushirish »
TCP server (net.Server)
TCP serveri net.createServer() usuli yordamida yaratiladi:
const net = require('net');
// Create a TCP server
const server = net.createServer((socket) => {
console.log('Client connected');
// Handle data from client
socket.on('data', (data) => {
console.log(`Received: ${data}`);
socket.write(`Echo: ${data}`);
});
// Handle client disconnection
socket.on('end', () => {
console.log('Client disconnected');
});
// Handle socket errors
socket.on('error', (err) => {
console.error(`Socket error: ${err.message}`);
});
});
// Start the server
const PORT = 8888;
server.listen(PORT, () => {
console.log(`TCP server listening on port ${PORT}`);
});
// Get server information after it's listening
server.on('listening', () => {
const address = server.address();
console.log(`Server info: ${JSON.stringify(address)}`);
});
Misolni ishga tushirish »
TLS/SSL server
Xavfsiz TLS/SSL server tls.createServer() usuli yordamida yaratiladi:
const tls = require('tls');
const fs = require('fs');
// SSL options
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
// Request client certificate (optional)
requestCert: true,
// Reject connections without certificates (optional)
rejectUnauthorized: false
};
// Create a TLS server
const server = tls.createServer(options, (socket) => {
console.log('Client connected securely');
// Check if client provided a certificate
if (socket.authorized) {
console.log('Client authorized');
} else {
console.log('Client unauthorized');
}
// Handle data from client
socket.on('data', (data) => {
console.log(`Received: ${data}`);
socket.write(`Secure echo: ${data}`);
});
// Handle client disconnection
socket.on('end', () => {
console.log('Client disconnected');
});
});
// Start the server
const PORT = 8443;
server.listen(PORT, () => {
console.log(`TLS server listening on port ${PORT}`);
});
Misolni ishga tushirish »
Marshrutlash bilan HTTP serveri
Asosiy marshrutlash bilan to‘liqroq HTTP serveri:
const http = require('http');
const url = require('url');
// Create an HTTP server with routing
const server = http.createServer((req, res) => {
// Parse the URL
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname;
const trimmedPath = path.replace(/^\/+|\/+$/g, '');
// Get the HTTP method
const method = req.method.toLowerCase();
// Get query parameters
const queryParams = parsedUrl.query;
// Log the request
console.log(`Request received: ${method} ${trimmedPath}`);
// Route handler
let response = {
status: 404,
contentType: 'application/json',
payload: { message: 'Not Found' }
};
// Basic routing
if (method === 'get') {
if (trimmedPath === '') {
// Home route
response = {
status: 200,
contentType: 'text/html',
payload: '<h1>Home Page</h1><p>Welcome to the server</p>'
};
} else if (trimmedPath === 'api/users') {
// API route - list users
response = {
status: 200,
contentType: 'application/json',
payload: {
users: [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
]
}
};
} else if (trimmedPath.startsWith('api/users/')) {
// API route - get user by ID
const userId = trimmedPath.split('/')[2];
response = {
status: 200,
contentType: 'application/json',
payload: { id: userId, name: `User ${userId}` }
};
}
}
// Return the response
res.setHeader('Content-Type', response.contentType);
res.writeHead(response.status);
// Convert payload to string if it's an object
const payloadString = typeof response.payload === 'object'
? JSON.stringify(response.payload)
: response.payload;
res.end(payloadString);
});
// Start the server
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Misolni ishga tushirish »
Serverning kutish vaqti va chegaralari
Serverning kutish vaqti va ulanish chegaralarini sozlash:
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// Simulating a delayed response
setTimeout(() => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Response after delay\n');
}, 2000);
});
// Configure server timeouts
server.timeout = 10000; // 10 seconds (default is 120000 or 2 minutes)
server.keepAliveTimeout = 5000; // 5 seconds (default is 5000)
server.maxHeadersCount = 1000; // Maximum headers count (default is 2000)
server.maxRequestsPerSocket = 100; // Max requests per socket (Node.js 14+)
// Start the server
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Server with timeouts configured at http://localhost:${PORT}/`);
// Display the server configuration
console.log(`Server timeout: ${server.timeout}ms`);
console.log(`Keep-alive timeout: ${server.keepAliveTimeout}ms`);
console.log(`Max headers count: ${server.maxHeadersCount}`);
console.log(`Max requests per socket: ${server.maxRequestsPerSocket || 'N/A'}`);
});
Misolni ishga tushirish »
HTTP/2 server
HTTP/2 serverini yaratish (Node.js v8.4.0 da kiritilgan):
const http2 = require('http2');
const fs = require('fs');
// SSL options for HTTP/2
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
};
// Create an HTTP/2 server
const server = http2.createSecureServer(options);
// Handle incoming streams
server.on('stream', (stream, headers) => {
const path = headers[':path'];
const method = headers[':method'];
console.log(`${method} ${path}`);
// Respond to the request
stream.respond({
'content-type': 'text/html',
':status': 200
});
stream.end('<h1>HTTP/2 Server</h1><p>This page was served via HTTP/2</p>');
});
// Start the server
const PORT = 8443;
server.listen(PORT, () => {
console.log(`HTTP/2 server running at https://localhost:${PORT}/`);
});
Misolni ishga tushirish »
Eng yaxshi amaliyotlar
- Xatoni qayta ishlash: Har doim "xato" hodisasini tinglash orqali server xatolarini hal qiling.
- Aqlli o‘chirish:
server.close()yordamida tegishli o‘chirish tartib-qoidalarini amalga oshiring. - Vaqt tugashi: Resurs tugashining oldini olish uchun tegishli vaqtni sozlang.
- Klasterlash: Bir nechta protsessor yadrolaridan foydalanish uchun
clustermodulidan foydalaning. - HTTPS/TLS: Ishlab chiqarish ilovalari uchun xavfsiz serverlardan foydalaning.
- Ulanish cheklovlari: Serveringiz imkoniyatlaridan kelib chiqqan holda tegishli cheklovlarni o‘rnating.
- Monitoring: Ulanishlar, so‘rovlar va javob vaqtlari uchun monitoringni amalga oshirish.
W3Schools Pathfinder
Yutuqlaringizni kuzating – bu bepul!
