Skip to main content

网络编程

1. Socket 编程

1.1 TCP Socket

服务端

const net = require('net');

const server = net.createServer((socket) => {
console.log('Client connected');

// 设置编码
socket.setEncoding('utf8');

// 接收数据
socket.on('data', (data) => {
console.log('Received:', data);
// 发送响应
socket.write('Server received: ' + data);
});

// 错误处理
socket.on('error', (err) => {
console.error('Socket error:', err);
});

// 连接关闭
socket.on('close', () => {
console.log('Client disconnected');
});
});

// 错误处理
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.error('Port is already in use');
}
});

server.listen(3000, () => {
console.log('Server listening on port 3000');
});

客户端

const net = require('net');

const client = new net.Socket();

// 连接服务器
client.connect(3000, 'localhost', () => {
console.log('Connected to server');

// 发送数据
client.write('Hello Server!');
});

// 接收数据
client.on('data', (data) => {
console.log('Received:', data);
});

// 错误处理
client.on('error', (err) => {
console.error('Connection error:', err);
});

// 连接关闭
client.on('close', () => {
console.log('Connection closed');
});

1.2 UDP Socket

服务端

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(`Server received: ${msg}`, rinfo.port, rinfo.address);
});

server.on('listening', () => {
const address = server.address();
console.log(`Server listening on ${address.address}:${address.port}`);
});

server.bind(3000);

客户端

const dgram = require('dgram');
const client = dgram.createSocket('udp4');

const message = Buffer.from('Hello Server!');
client.send(message, 3000, 'localhost', (err) => {
if (err) {
console.error('Failed to send message');
} else {
console.log('Message sent');
}
});

client.on('message', (msg, rinfo) => {
console.log(`Received: ${msg} from ${rinfo.address}:${rinfo.port}`);
client.close();
});

2. WebSocket

2.1 服务端实现

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
console.log('New client connected');

// 发送欢迎消息
ws.send('Welcome to the WebSocket server!');

// 接收消息
ws.on('message', (message) => {
console.log('Received:', message);

// 广播消息给所有客户端
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});

// 错误处理
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});

// 连接关闭
ws.on('close', () => {
console.log('Client disconnected');
});
});

2.2 客户端实现

// 建立连接
const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
console.log('Connected to server');

// 发送消息
ws.send('Hello from client!');
};

ws.onmessage = (event) => {
console.log('Received:', event.data);
};

ws.onerror = (error) => {
console.error('WebSocket error:', error);
};

ws.onclose = () => {
console.log('Disconnected from server');
};

// 心跳检测
function heartbeat() {
if (!ws) return;
if (ws.readyState !== 1) return;

ws.send('ping');
setTimeout(heartbeat, 30000);
}

2.3 实时聊天示例

// 服务端
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

const clients = new Map();

wss.on('connection', (ws) => {
const id = generateId();
const color = generateColor();
const metadata = { id, color };

clients.set(ws, metadata);

ws.on('message', (messageAsString) => {
const message = JSON.parse(messageAsString);
const metadata = clients.get(ws);

message.sender = metadata.id;
message.color = metadata.color;

[...clients.keys()].forEach((client) => {
client.send(JSON.stringify(message));
});
});

ws.on('close', () => {
clients.delete(ws);
});
});

// 客户端
const ws = new WebSocket('ws://localhost:8080');

ws.onmessage = (event) => {
const message = JSON.parse(event.data);

addMessageToChat(message);
};

function sendMessage(text) {
const message = {
text,
timestamp: Date.now()
};

ws.send(JSON.stringify(message));
}

3. HTTP/HTTPS 服务器

3.1 HTTP 服务器

const http = require('http');

const server = http.createServer((req, res) => {
// CORS 设置
res.setHeader('Access-Control-Allow-Origin', '*');

// 路由处理
if (req.url === '/api/data' && req.method === 'GET') {
handleGetData(req, res);
} else if (req.url === '/api/user' && req.method === 'POST') {
handleCreateUser(req, res);
} else {
res.writeHead(404);
res.end('Not Found');
}
});

server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});

3.2 HTTPS 服务器

const https = require('https');
const fs = require('fs');

const options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('certificate.pem')
};

const server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Hello Secure World\n');
});

server.listen(443, () => {
console.log('Server running at https://localhost/');
});