@hexys/midwayjs-tcp
TypeScript icon, indicating that this package has built-in type declarations

0.0.5 • Public • Published

Midway TCP 组件

1. 安装

npm i @hexys/midwayjs-tcp

项目中引用并配置

// src/configuration.ts

import * as tcp from '@hexys/midwayjs-tcp';

@Configuration({
  imports: [tcp],
  importConfigs: [join(__dirname, './config')],
})
export class ContainerLifeCycle implements ILifeCycle {
  // ...
}

2. 使用

1. 依赖注入

export class TCPService {
  @Inject('tcp:manager')
  tcpClientManager: TCPClientManager;
}

2. 连接

TCPClientOptions 为连接参数配置项

interface TCPClientOptions {
  host: string;
  port: number;
  // 重连时间,单位毫秒
  reconnect?: number;
  logger?: ILogger;
  type?: MessageType;
  onconnect?: (TCPClientOptions) => any;
  onclose?: (TCPClientOptions) => any;
  ondata?: (TCPClientOptions) => any;
}

MessageType 标识消息类型,RCU、PMS 或没有类型

enum MessageType {
  RCU = 'rcu',
  PMS = 'pms',
  NONE = '',
}

使用配置项发起 TCP 连接,如果已有相同配置连接,则复用。否则建立新连接。

const tcpClient = this.tcpClientManager.connect({
  host: host,
  port: parseInt(port),
  reconnect: 1000,
  type: type || MessageType.NONE,
});

3. 发送消息/关闭连接

// 发送消息
tcpClient.send(message);

// 关闭连接
tcpClientManager.destroy({host, port});

4. TCP 事件处理装饰器

连接事件装饰器

@OnConnect()
async onconnect({ port, host, type }) {
  // ...
}

关闭事件装饰器

@OnClose()
async onclose({ port, host, type }) {
  // ...
}

消息事件装饰器

@OnData()
async ondata({ port, host, type, buffer }) {
  // ...
}

Readme

Keywords

none

Package Sidebar

Install

npm i @hexys/midwayjs-tcp

Weekly Downloads

0

Version

0.0.5

License

MIT

Unpacked Size

18 kB

Total Files

16

Last publish

Collaborators

  • zhagqn