@zenweb/websocket
v3.2.0
Published
Zenweb WebSocket module
Downloads
72
Maintainers
Readme
ZenWeb WebSocket module
import { $debug, $query, Context, mapping } from 'zenweb';
import { WebSocket, RedisSocketSession } from '@zenweb/websocket';
export class Controller {
@mapping()
index(ctx: Context) {
ctx.template('index.njk');
return { name: 'Hello' };
}
@mapping()
async ws(ws: WebSocket, ss: RedisSocketSession) {
$debug('websocket 连接');
const { name } = await $query.get({ name: '!trim1' });
const room = 'chat';
await ss.add(room, ws);
ss.send(room, `欢迎 ${name} 来到聊天室!`);
ws.once('close', () => {
ss.send(room, `${name} 离开了聊天室!`);
});
ws.on('message', data => {
const str = data.toString();
ss.send(room, name + ': ' + str);
});
}
}