9.2 WebSocket 通信

服务器端

1
2
3
4
5
6
7
8
9
10
11
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 3000 });

wss.on('connection', (ws) => {
ws.on('message', async (data) => {
const message = JSON.parse(data);
const response = await handleMessage(message);
ws.send(JSON.stringify(response));
});
});

客户端

1
2
3
4
5
6
7
8
9
10
const ws = new WebSocket('ws://localhost:3000');

ws.on('open', () => {
ws.send(JSON.stringify({ type: 'chat.send', content: '你好' }));
});

ws.on('message', (data) => {
const response = JSON.parse(data);
console.log(response);
});

导航

上一篇: 9.1 客户端-服务器分离

下一篇: 9.3 并发连接管理