为什么需要 WebSocket?
#服务端实现
# 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
const session = openclaw.session.create();
ws.on('message', async (message) => {
const data = JSON.parse(message);
// 流式响应
await session.chat(data.content, {
stream: true,
onChunk: (chunk) => {
ws.send(JSON.stringify({
type: 'chunk',
content: chunk
}));
}
});
});
});
|
客户端连接
# 1
2
3
4
5
6
7
8
9
10
11
12
13
14
| const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'chunk') {
appendToUI(data.content);
}
};
// 发送消息
ws.send(JSON.stringify({
content: '你好'
}));
|
WebSocket 让 OpenClaw 实现真正的实时交互。