Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@thallo/api-websocket

kettyy.45MIT1.1.4TypeScript support: included

前端连接阿里 API 网关 websocket 的 SDK【TypeScript 版】。 > > 处理网关响应的各种信令,已集成重连机制,可自动重连,支持手动重连。

readme

前端连接阿里 API 网关 websocket 的 SDK【TypeScript 版】。

处理网关响应的各种信令,已集成重连机制,可自动重连,支持手动重连。

Usage

依赖@thallo/api-signature

yarn add @thallo/api-websocket @thallo/api-signature
import WebsocketApiClient from "@thallo/api-websocket";
import ApiSignature from "@thallo/api-signature";

const Signature = new ApiSignature({
  appKey: "test",
  appSecret: "test",
  stage: "RELEASE",
});

const socket = new WebsocketApiClient({
  host: "www.test.com", // 域名
  appKey: "test", // app key
  Signature, // 签名实例
  registerMethod: "POST", // 注册请求方法
  registerPath: "/register", // 注册路由
  logoutMethod: "POST", // 注销请求方法
  logoutPath: "/logout", // 注销路由
});

// 设置注册参数,参数可选
// socket.setRegisterOptions({
//   headers:{
//     "x-token":"XXXXXXXXX"
//   }
//   params:{
//     id:"xxxxxxxx"
//   },
//   data:{
//     password:"xxxxxxxxxx"
//   }
// })

// 设置注销参数,参数可选,若不设置默认与注册参数相同
// socket.setLogoutOptions({
//   headers:{
//     "x-token":"XXXXXXXXX"
//   }
//   params:{
//     id:"xxxxxxxx"
//   },
//   data:{
//     password:"xxxxxxxxxx"
//   }
// })

// 主动连接websocket,默认不连接
socket.connect();

// 监听下发通知
socket.onNotify = (message: string) => {
  // do something
};

// 注销
socket.logout();