Net தொகுதிக்கு அறிமுகம்
Net தொகுதி Node.js இன் முக்கிய வலையமைப்பு தொகுதிகளில் ஒன்றாகும், இது TCP சேவையகங்கள் மற்றும் கிளையன்ட்களை உருவாக்க உங்களை அனுமதிக்கிறது. TCP (Transmission Control Protocol) என்பது வலையமைப்பு சாதனங்களில் இயங்கும் பயன்பாடுகளுக்கு இடையே பைட்டுகளின் ஸ்ட்ரீமின் நம்பகமான, வரிசைப்படுத்தப்பட்ட மற்றும் பிழை-சரிபார்க்கப்பட்ட விநியோகமாகும்.
HTTP தொகுதியை விட, இது Net தொகுதியின் மேல் கட்டப்பட்டது, Net தொகுதி குறைந்த-நிலை வலையமைப்பு திறன்களை வழங்குகிறது, இது தகவல்தொடர்பு நெறிமுறையில் அதிக கட்டுப்பாட்டை வழங்குகிறது.
குறிப்பு:
Net தொகுதி தனிப்பயன் TCP நெறிமுறை தேவைப்படும் சூழ்நிலைகளுக்கு அல்லது TCP மேல் உங்கள் சொந்த பயன்பாடு-நிலை நெறிமுறையை செயல்படுத்த விரும்பும் போது மிகவும் பொருத்தமானது.
Net தொகுதியை இறக்குமதி செய்தல்
Net தொகுதியைப் பயன்படுத்த, அதை உங்கள் Node.js பயன்பாட்டில் require() முறையைப் பயன்படுத்தி சேர்க்கவும்:
const net = require('net');
TCP சேவையகத்தை உருவாக்குதல்
Net தொகுதி இணைப்புகளைக் கேட்கும் TCP சேவையகத்தை உருவாக்க எளிதாக்குகிறது:
const net = require('net');
// Create a TCP server
const server = net.createServer((socket) => {
console.log('Client connected');
// Set encoding to utf8 so we receive strings instead of Buffer objects
socket.setEncoding('utf8');
// Handle data from client
socket.on('data', (data) => {
console.log(`Received from client: ${data}`);
// Echo the data back to the client
socket.write(`Echo: ${data}`);
});
// Handle client disconnection
socket.on('end', () => {
console.log('Client disconnected');
});
// Handle errors
socket.on('error', (err) => {
console.error('Socket error:', err);
});
// Send a welcome message to the client
socket.write('Welcome to the TCP server!\r\n');
});
// Start the server and listen on port 8080
server.listen(8080, () => {
console.log('TCP Server running on port 8080');
});
இந்த எடுத்துக்காட்டில்:
TCP கிளையன்ட் உருவாக்குதல்
நீங்கள் TCP சேவையகத்துடன் இணைய TCP கிளையன்ட் ஒன்றையும் உருவாக்கலாம்:
const net = require('net');
// Create a TCP client
const client = net.createConnection({ port: 8080 }, () => {
console.log('Connected to server');
// Send a message to the server
client.write('Hello from client!');
});
// Set encoding
client.setEncoding('utf8');
// Handle data from server
client.on('data', (data) => {
console.log(`Received from server: ${data}`);
// Send another message
client.write('More data from client');
});
// Handle connection end
client.on('end', () => {
console.log('Disconnected from server');
});
// Handle errors
client.on('error', (err) => {
console.error('Connection error:', err);
});
இந்த எடுத்துக்காட்டில்:
சோதனை குறிப்பு:
கிளையன்ட் மற்றும் சேவையகத்தை ஒன்றாக சோதிக்க, ஒரு டெர்மினலில் சேவையக ஸ்கிரிப்ட் மற்றும் மற்றொரு டெர்மினலில் கிளையன்ட் ஸ்கிரிப்ட் இயக்கவும்.
சாக்கெட் பண்புகள் மற்றும் முறைகள்
சேவையக இணைப்பு கால்பேக்கிற்கு வழங்கப்பட்ட மற்றும் createConnection() மூலம் திரும்பப் பெறப்பட்ட Socket பொருளில் பல பயனுள்ள பண்புகள் மற்றும் முறைகள் உள்ளன:
| பண்பு/முறை | விளக்கம் |
|---|---|
| socket.write(data[, encoding][, callback]) | சாக்கெட்டில் தரவை எழுதுகிறது, விருப்பமாக குறிப்பிட்ட குறியாக்கத்துடன் |
| socket.end([data][, encoding][, callback]) | அனைத்து தரவும் எழுதப்பட்டு ப்ளஷ் செய்யப்பட்ட பிறகு சாக்கெட்டை மூடுகிறது |
| socket.setEncoding(encoding) | சாக்கெட்டில் பெறப்பட்ட தரவுக்கான குறியாக்கத்தை அமைக்கிறது |
| socket.setTimeout(timeout[, callback]) | செயலற்ற தன்மையின் குறிப்பிட்ட மில்லி விநாடிகளுக்குப் பிறகு சாக்கெட்டை டைம்அவுட்டுக்கு அமைக்கிறது |
| socket.setKeepAlive([enable][, initialDelay]) | கீப்-அலைவு செயல்பாட்டை இயக்குகிறது/முடக்குகிறது |
| socket.address() | இணைப்பின் முகவரி, குடும்பம் மற்றும் போர்ட்டுடன் ஒரு பொருளை வழங்குகிறது |
| socket.remoteAddress | தொலை IP முகவரி ஒரு சரமாக |
| socket.remotePort | தொலை போர்ட் ஒரு எண்ணாக |
| socket.localAddress | சேவையகம் கேட்கும் உள்ளூர் IP முகவரி |
| socket.localPort | சேவையகம் கேட்கும் உள்ளூர் போர்ட் |
| socket.bytesRead | பெறப்பட்ட பைட்டுகளின் எண்ணிக்கை |
| socket.bytesWritten | அனுப்பப்பட்ட பைட்டுகளின் எண்ணிக்கை |
சேவையக பண்புகள் மற்றும் முறைகள்
createServer() மூலம் திரும்பப் பெறப்பட்ட Server பொருளில் இந்த பயனுள்ள பண்புகள் மற்றும் முறைகள் உள்ளன:
| பண்பு/முறை | விளக்கம் |
|---|---|
| server.listen(port[, hostname][, backlog][, callback]) | இணைப்புகளைக் கேட்க சேவையகத்தைத் தொடங்குகிறது |
| server.close([callback]) | புதிய இணைப்புகளை ஏற்க சேவையகத்தை நிறுத்துகிறது |
| server.address() | சேவையகத்தின் முகவரி தகவலுடன் ஒரு பொருளை வழங்குகிறது |
| server.maxConnections | இணைப்பு எண்ணிக்கை அதிகரித்தால் இணைப்புகளை நிராகரிக்க இந்த பண்பை அமைக்கவும் |
| server.connections | ஒரே நேர இணைப்புகளின் எண்ணிக்கை |
| server.listening | சேவையகம் கேட்கிறதா என்பதைக் குறிக்கும் பூலியன் |
அரட்டை சேவையகத்தை உருவாக்குதல்
அனைத்து இணைக்கப்பட்ட கிளையன்ட்களுக்கும் செய்திகளை ஒலிபரப்பும் ஒரு எளிய அரட்டை சேவையகத்தை உருவாக்கலாம்:
const net = require('net');
// Store all client connections
const clients = [];
// Create a chat server
const server = net.createServer((socket) => {
// Generate a client ID
const clientId = `${socket.remoteAddress}:${socket.remotePort}`;
console.log(`Client connected: ${clientId}`);
// Set encoding
socket.setEncoding('utf8');
// Add client to the list
clients.push(socket);
// Send welcome message
socket.write(`Welcome to the chat server! There are ${clients.length} users online.\r\n`);
// Broadcast message to all clients except the sender
function broadcast(message, sender) {
clients.forEach(client => {
if (client !== sender) {
client.write(message);
}
});
}
// Notify all clients about the new connection
broadcast(`User ${clientId} joined the chat.\r\n`, socket);
// Handle client messages
socket.on('data', (data) => {
console.log(`${clientId}: ${data.trim()}`);
// Broadcast the message to all other clients
broadcast(`${clientId}: ${data}`, socket);
});
// Handle client disconnection
socket.on('end', () => {
console.log(`Client disconnected: ${clientId}`);
// Remove client from the list
const index = clients.indexOf(socket);
if (index !== -1) {
clients.splice(index, 1);
}
// Notify all clients about the disconnection
broadcast(`User ${clientId} left the chat.\r\n`, null);
});
// Handle errors
socket.on('error', (err) => {
console.error(`Socket error from ${clientId}:`, err);
});
});
// Start the server
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Chat server running on port ${PORT}`);
});
// Handle server errors
server.on('error', (err) => {
console.error('Server error:', err);
});
இந்த அரட்டை சேவையகத்துடன் இணைய, நீங்கள் TCP கிளையன்ட் அல்லது telnet போன்ற டெர்மினல் கருவியைப் பயன்படுத்தலாம்:
telnet localhost 8080
நீங்கள் Net தொகுதியைப் பயன்படுத்தி ஒரு அர்ப்பணிக்கப்பட்ட அரட்டை கிளையன்ட் ஒன்றையும் உருவாக்கலாம்:
const net = require('net');
const readline = require('readline');
// Create interface for reading from the terminal
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Create a client connection
const client = net.createConnection({ port: 8080 }, () => {
console.log('Connected to chat server');
console.log('Type a message and press Enter to send');
// Start reading user input
rl.prompt();
});
// Set encoding
client.setEncoding('utf8');
// Handle data from server
client.on('data', (data) => {
// Move cursor to beginning of line and clear it
process.stdout.write('\r\x1b[K');
// Print the server message
console.log(data.trim());
// Re-display the prompt
rl.prompt();
});
// Handle connection end
client.on('end', () => {
console.log('Disconnected from server');
rl.close();
process.exit(0);
});
// Handle errors
client.on('error', (err) => {
console.error('Connection error:', err);
rl.close();
process.exit(1);
});
// Handle user input
rl.on('line', (input) => {
// Send the user input to the server
client.write(input);
rl.prompt();
});
// Close the connection when the user exits
rl.on('close', () => {
console.log('Exiting chat...');
client.end();
});
ஒரு எளிய நெறிமுறையை உருவாக்குதல்
Net தொகுதியைப் பயன்படுத்துவதன் நன்மைகளில் ஒன்று உங்கள் சொந்த பயன்பாட்டு நெறிமுறைகளை உருவாக்கும் திறன் ஆகும். ஒரு எளிய JSON-அடிப்படையிலான நெறிமுறையை உருவாக்கலாம்:
const net = require('net');
// Create a server that supports a JSON-based protocol
const server = net.createServer((socket) => {
console.log('Client connected');
// Buffer for incoming data
let buffer = '';
// Handle data
socket.on('data', (data) => {
// Add the new data to our buffer
buffer += data.toString();
// Process complete messages
let boundary = buffer.indexOf('\n');
while (boundary !== -1) {
// Extract the complete message
const message = buffer.substring(0, boundary);
buffer = buffer.substring(boundary + 1);
// Process the message
try {
const parsedMessage = JSON.parse(message);
console.log('Received message:', parsedMessage);
// Handle different message types
switch (parsedMessage.type) {
case 'greeting':
socket.write(JSON.stringify({
type: 'welcome',
message: `Hello, ${parsedMessage.name}!`,
timestamp: Date.now()
}) + '\n');
break;
case 'query':
socket.write(JSON.stringify({
type: 'response',
queryId: parsedMessage.queryId,
result: handleQuery(parsedMessage.query),
timestamp: Date.now()
}) + '\n');
break;
default:
socket.write(JSON.stringify({
type: 'error',
message: 'Unknown message type',
timestamp: Date.now()
}) + '\n');
}
} catch (err) {
console.error('Error processing message:', err);
socket.write(JSON.stringify({
type: 'error',
message: 'Invalid JSON format',
timestamp: Date.now()
}) + '\n');
}
// Look for the next message
boundary = buffer.indexOf('\n');
}
});
// Handle disconnection
socket.on('end', () => {
console.log('Client disconnected');
});
// Handle errors
socket.on('error', (err) => {
console.error('Socket error:', err);
});
});
// Simple function to handle queries
function handleQuery(query) {
if (query === 'time') {
return { time: new Date().toISOString() };
} else if (query === 'stats') {
return {
uptime: process.uptime(),
memory: process.memoryUsage(),
platform: process.platform
};
} else {
return { error: 'Unknown query' };
}
}
// Start the server
const PORT = 8080;
server.listen(PORT, () => {
console.log(`JSON protocol server running on port ${PORT}`);
});
இந்த நெறிமுறையைப் பயன்படுத்தும் ஒரு கிளையன்ட் இங்கே:
const net = require('net');
// Connect to the server
const client = net.createConnection({ port: 8080 }, () => {
console.log('Connected to server');
// Send a greeting
send({
type: 'greeting',
name: 'Client'
});
// Send a query
send({
type: 'query',
queryId: 1,
query: 'time'
});
// Send another query
setTimeout(() => {
send({
type: 'query',
queryId: 2,
query: 'stats'
});
}, 1000);
});
// Buffer for incoming data
let buffer = '';
// Handle data from server
client.on('data', (data) => {
// Add the new data to our buffer
buffer += data.toString();
// Process complete messages
let boundary = buffer.indexOf('\n');
while (boundary !== -1) {
// Extract the complete message
const message = buffer.substring(0, boundary);
buffer = buffer.substring(boundary + 1);
// Process the message
try {
const parsedMessage = JSON.parse(message);
console.log('Received from server:', parsedMessage);
} catch (err) {
console.error('Error parsing message:', err);
}
// Look for the next message
boundary = buffer.indexOf('\n');
}
});
// Helper function to send messages
function send(message) {
const jsonString = JSON.stringify(message) + '\n';
console.log('Sending:', message);
client.write(jsonString);
}
// Handle connection end
client.on('end', () => {
console.log('Disconnected from server');
});
// Handle errors
client.on('error', (err) => {
console.error('Connection error:', err);
});
// Close the connection after some time
setTimeout(() => {
console.log('Closing connection');
client.end();
}, 5000);
நெறிமுறை குறிப்பு:
இந்த நெறிமுறையில், செய்தி தொடர்முறைக்கு JSON ஐப் பயன்படுத்துகிறோம் மற்றும் செய்தி எல்லைகளுக்கு புதிய வரி எழுத்துகளை (\n) பயன்படுத்துகிறோம். இது செய்திகளை பாகுபடுத்துவதை எளிதாக்குகிறது மற்றும் பல்வேறு வகையான செய்திகள் மற்றும் பேலோடுகளை அனுமதிக்கிறது.
சாக்கெட் டைம்அவுட்கள்
செயலற்ற இணைப்புகளைக் கையாள, நீங்கள் சாக்கெட்டில் ஒரு டைம்அவுட்டை அமைக்கலாம்:
const net = require('net');
const server = net.createServer((socket) => {
console.log('Client connected');
// Set a timeout of 10 seconds
socket.setTimeout(10000);
// Handle timeout
socket.on('timeout', () => {
console.log('Socket timeout');
socket.write('You have been inactive for too long. Disconnecting...\r\n');
socket.end();
});
// Handle data
socket.on('data', (data) => {
console.log(`Received: ${data.toString().trim()}`);
socket.write(`Echo: ${data}`);
});
// Handle disconnection
socket.on('end', () => {
console.log('Client disconnected');
});
});
server.listen(8080, () => {
console.log('Server with timeout running on port 8080');
});
IPC உடன் பணிபுரிதல் (இடை-செயல்முறை தகவல்தொடர்பு)
Net தொகுதி Unix டொமைன் சாக்கெட்டுகள் அல்லது விண்டோஸில் பெயரிடப்பட்ட பைப்களைப் பயன்படுத்தி IPC (இடை-செயல்முறை தகவல்தொடர்பு) சேவையகங்கள் மற்றும் கிளையன்ட்களையும் உருவாக்க முடியும்:
const net = require('net');
const path = require('path');
// Define the path for the IPC socket
const socketPath = path.join(__dirname, 'ipc-socket');
// Create an IPC server
const server = net.createServer((socket) => {
console.log('Client connected to IPC server');
socket.on('data', (data) => {
console.log(`Received via IPC: ${data.toString().trim()}`);
socket.write(`Echo: ${data}`);
});
socket.on('end', () => {
console.log('Client disconnected from IPC server');
});
});
// Start the IPC server
server.listen(socketPath, () => {
console.log(`IPC server running at ${socketPath}`);
});
// Clean up the socket file when the server closes
server.on('close', () => {
console.log('Cleaning up socket file');
require('fs').unlinkSync(socketPath);
});
// Handle process termination
process.on('SIGINT', () => {
server.close(() => {
console.log('IPC server closed');
process.exit(0);
});
});
மற்றும் இங்கே ஒரு IPC கிளையன்ட் உள்ளது:
const net = require('net');
const path = require('path');
// Define the path for the IPC socket
const socketPath = path.join(__dirname, 'ipc-socket');
// Create an IPC client
const client = net.createConnection({ path: socketPath }, () => {
console.log('Connected to IPC server');
client.write('Hello from IPC client!');
});
client.on('data', (data) => {
console.log(`Received from IPC server: ${data.toString().trim()}`);
client.end();
});
client.on('end', () => {
console.log('Disconnected from IPC server');
});
client.on('error', (err) => {
console.error('Connection error:', err);
});
IPC நன்மைகள்:
Unix டொமைன் சாக்கெட்டுகள் அல்லது பெயரிடப்பட்ட பைப்களைப் பயன்படுத்தும் IPC இணைப்புகள் பொதுவாக TCP இணைப்புகளை விட வேகமானவை மற்றும் பாதுகாப்பானவை, ஏனெனில் அவை நெட்வொர்க் ஸ்டேக்கைப் பயன்படுத்துவதில்லை மற்றும் உள்ளூர் இயந்திரத்திற்கு மட்டுப்படுத்தப்பட்டுள்ளன.
சிறந்த நடைமுறைகள்
Net தொகுதி vs. HTTP தொகுதி
| அம்சம் | Net தொகுதி | HTTP தொகுதி |
|---|---|---|
| நெறிமுறை | மூல TCP/IP | HTTP நெறிமுறை |
| செய்தி வடிவம் | தனிப்பயன் (நீங்கள் வரையறுக்கிறீர்கள்) | HTTP கோரிக்கை/பதில் |
| சுருக்க நிலை | குறைந்த-நிலை, அதிக கட்டுப்பாடு | உயர்-நிலை, பயன்படுத்த எளிதானது |
| பயன்பாட்டு வழக்கு | தனிப்பயன் நெறிமுறைகள், செயல்திறன்-முக்கியமான பயன்பாடுகள் | வலை பயன்பாடுகள், REST APIகள் |
Net தொகுதியைப் பயன்படுத்தவும் போது:
- நீங்கள் ஒரு தனிப்பயன் நெறிமுறையை செயல்படுத்த வேண்டும்
- தகவல்தொடர்பில் அதிக கட்டுப்பாடு வேண்டும்
- செயல்திறனுக்காக மேம்படுத்த வேண்டும்
- நீங்கள் ஒரு அல்லாத-HTTP TCP சேவையகத்தை உருவாக்குகிறீர்கள் (அரட்டை, விளையாட்டு, முதலியன)
HTTP தொகுதியைப் பயன்படுத்தவும் போது:
- நீங்கள் ஒரு வலை சேவையகம் அல்லது API ஐ உருவாக்குகிறீர்கள்
- கோரிக்கை ரூட்டிங், தலைப்புகள் போன்ற HTTP-குறிப்பிட்ட அம்சங்கள் தேவை
- Express போன்ற உயர்-நிலை வலை கட்டமைப்புகளைப் பயன்படுத்த விரும்புகிறீர்கள்
சுருக்கம்
Node.js Net தொகுதி TCP சேவையகங்கள் மற்றும் கிளையன்ட்களை உருவாக்க சக்திவாய்ந்த கருவிகளை வழங்குகிறது. இது வழங்குகிறது:
தனிப்பயன் நெறிமுறைகளுக்கான குறைந்த-நிலை சாக்கெட் அணுகல்
இணைப்புகளைக் கையாளுவதற்கான அசிங்க்ரோனஸ், நிகழ்வு-இயக்கப்பட்ட API
TCP/IP மற்றும் IPC தகவல்தொடர்பு இரண்டிற்கும் ஆதரவு
உயர்-நிலை நெறிமுறைகளுக்கான கட்டுமானத் தொகுதிகள்
இது HTTP போன்ற உயர்-நிலை தொகுதிகளை விட அதிக கைமுறை வேலை தேவைப்படுகிறது, Net தொகுதி உங்கள் பயன்பாட்டிற்கு தேவையான நெறிமுறையை சரியாக செயல்படுத்த நெகிழ்வுத்தன்மையை வழங்குகிறது.
கண்காணிப்பு குறிப்பு:
உங்கள் TCP சேவையகத்தின் செயல்திறனை netstat, ss, அல்லது lsof போன்ற கருவிகளைப் பயன்படுத்தி எப்போதும் கண்காணிக்கவும், இதனால் தடைகள் மற்றும் இணைப்பு சிக்கல்களை அடையாளம் காணலாம்.