npm.io
3.4.0 • Published 7 months ago

@zenweb/websocket

Licence
MIT
Version
3.4.0
Deps
5
Size
20 kB
Vulns
0
Weekly
0

ZenWeb WebSocket module

ZenWeb

websocket 模块 - 支持分布式 websocket 会话共享

import { $debug, $query, Context, Get } from 'zenweb';
import { WebSocket, RedisSocketSession } from '@zenweb/websocket';

export class Controller {
  @Get()
  index(ctx: Context) {
    ctx.template('index.njk');
    return { name: 'Hello' };
  }

  @Get()
  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);
    });
  }
}

Keywords