1.0.10 • Published 3 years ago

koa-my-ws v1.0.10

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

koa-my-ws

基于 koa2 简单封装 websocket,集成心跳检测,广播消息等功能

安裝

npm i koa-my-ws

基本使用

const Koa = require("koa");
const Router = require("koa-router");
const app = new Koa();
const { createWsServer, upgradeWs, broadcastClient } = require("koa-my-ws");
// 创建ws服务,设置心跳检测时间
app.use(createWsServer({ checkTime: 3000 }));

const router = new Router();
router.get("/ws/:id", async (ctx, next) => {
  const { id } = ctx.params;
  // 升级协议 返回当前ws对象 第二个参数可以携带自定义唯一id
  let ws = await upgradeWs(ctx, id);
  if (ws) {
    ws.on("message", data => {
      console.log(data);
    });
  }
  next();
});

app.use(router.routes());
app.listen(3000);

内置方法

createWsServer(wsOptions)

创建一个 websocket 服务,返回一个中间件

wsOptions(可选)描述默认值
heartbeat是否开启心跳检测(如果服务端 ping 不通客户端,客户端将删除这个连接)true
checkTime检测心跳轮询时间30000
...options合并 ws 的基本配置options

upgradeWs(ctx,clientId,state)

升级协议,返回当前 ws 客户端

参数描述默认值
ctx(必选)当前上下文null
clientId(可选)指定连接的唯一 建议用户 id 或者 token 等建立关联null
state(可选)自定义数据 挂载在 ws 对象上方便后续可能使用{}

broadcastClient(data,clientId)

发送广播消息,将发送给当前已连接的所有 ws 客户端,可选指定的 clientId 发送

参数描述默认值
data(必选)消息内容null
clientId(可选)指定 id 发送null

getClients(clientId)

根据 clientId 获取 ws 客户端 返回数组,不传则返回全部

参数描述默认值
clientId(可选)指定 idnull

getClientNumber()

获取当前已连接客户端数量

1.0.9

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.10

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago