在Linux环境下使用Node.js进行网络编程,主要依赖于内置的http
、https
、net
、dgram
等模块。以下是一些基本的网络编程示例:
http
模块):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/');
});
https
模块):const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('your-private-key.pem'),
cert: fs.readFileSync('your-certificate.pem')
};
const server = https.createServer(options, (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3001, () => {
console.log('Server running at https://localhost:3001/');
});
net
模块):const net = require('net');
const client = new net.Socket();
client.connect(3002, 'localhost', () => {
console.log('Connected to server');
client.write('Hello Server!');
});
client.on('data', (data) => {
console.log(`Received data: ${data}`);
client.destroy(); // 关闭连接
});
client.on('close', () => {
console.log('Connection closed');
});
dgram
模块):const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('listening', () => {
const address = server.address();
console.log(`Server listening ${address.address}:${address.port}`);
});
server.on('message', (msg, rinfo) => {
console.log(`Server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.bind(3003);
dgram
模块):const dgram = require('dgram');
const client = dgram.createSocket('udp4');
const message = Buffer.from('Hello Server!');
client.send(message, 3003, 'localhost', (err) => {
if (err) throw err;
console.log('Message sent!');
});
client.on('listening', () => {
const address = client.address();
console.log(`Client listening ${address.address}:${address.port}`);
});
client.on('message', (msg, rinfo) => {
console.log(`Client received: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
这些示例展示了如何在Linux环境下使用Node.js进行基本的网络编程。你可以根据自己的需求选择合适的模块和方法进行开发。