温馨提示×

Node.js在Linux上的网络编程

小樊
51
2025-10-16 06:52:11
栏目: 编程语言

Installing Node.js on Linux
Before starting network programming, you need to install Node.js and npm (Node Package Manager) on your Linux system. For Ubuntu/Debian-based distributions, run the following commands in the terminal:

sudo apt update sudo apt install nodejs npm 

Verify the installation by checking the versions:

node -v # Should display the installed Node.js version (e.g., v18.x.x) npm -v # Should display the installed npm version (e.g., 9.x.x) 

This ensures you have the necessary tools to run Node.js applications.

Basic Network Programming with Built-in Modules
Node.js provides several built-in modules for network programming, including http/https (for HTTP/HTTPS servers), net (for TCP servers/clients), and dgram (for UDP servers/clients). Below are fundamental examples of each:

1. HTTP Server

The http module enables creating web servers. The following example creates a simple HTTP server that responds with “Hello World” to all requests:

const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); }); 

Save this code as server.js and run it with node server.js. Access http://localhost:3000 in a browser to see the response.

2. TCP Server and Client

The net module facilitates TCP communication. Below is a TCP server that echoes back any data it receives from a client, along with a corresponding client to test it:

TCP Server

const net = require('net'); const server = net.createServer((socket) => { console.log('Client connected'); socket.on('data', (data) => { console.log(`Received: ${data}`); socket.write(`Echo: ${data}`); }); socket.on('end', () => { console.log('Client disconnected'); }); }); server.listen(3001, () => { console.log('TCP Server listening on port 3001'); }); 

Save as tcp_server.js and run with node tcp_server.js.

TCP Client

const net = require('net'); const client = net.createConnection(3001, '127.0.0.1', () => { console.log('Connected to TCP server'); client.write('Hello from client!'); }); client.on('data', (data) => { console.log(`Received: ${data}`); client.end(); }); client.on('end', () => { console.log('Disconnected from server'); }); 

Save as tcp_client.js and run with node tcp_client.js. The client will send a message to the server, which will echo it back.

3. UDP Server and Client

The dgram module enables UDP communication (connectionless, faster but less reliable than TCP). Below is a UDP server that responds to incoming messages and a client to test it:

UDP Server

const dgram = require('dgram'); const server = dgram.createSocket('udp4'); server.on('message', (msg, rinfo) => { console.log(`Received: ${msg} from ${rinfo.address}:${rinfo.port}`); server.send(`Echo: ${msg}`, rinfo.port, rinfo.address); }); server.bind(3002, () => { console.log('UDP Server listening on port 3002'); }); 

Save as udp_server.js and run with node udp_server.js.

UDP Client

const dgram = require('dgram'); const client = dgram.createSocket('udp4'); const message = Buffer.from('Hello from UDP client!'); client.send(message, 3002, '127.0.0.1', (err) => { if (err) throw err; console.log('Message sent to server'); client.close(); }); 

Save as udp_client.js and run with node udp_client.js. The client sends a UDP packet to the server, which responds with an echo.

Testing with Command-Line Tools
You can use standard Linux tools to test your servers without writing additional clients:

  • TCP: Use telnet (install with sudo apt install telnet) or nc (netcat, install with sudo apt install netcat) to connect to the TCP server:
    telnet localhost 3001 # Or nc localhost 3001 
    Type a message and press Enter to see the server’s echo response.
  • UDP: Use nc in UDP mode to test the UDP server:
    nc -u localhost 3002 
    Type a message and press Enter—the server will respond with an echo.

Advanced Tips
For more complex scenarios (e.g., HTTPS, HTTP/2, WebSocket), explore additional Node.js modules like https (for secure HTTP servers), http2 (for HTTP/2 protocol), or third-party libraries like ws (for WebSocket). Refer to the official Node.js documentation for detailed guides and API references.

0