# @hexys/midwayjs-tcp

> ## 1. 安装

Latest version **0.0.5** (published 2021-09-24) · MIT license · 0 weekly downloads

## Install

```sh
npm install @hexys/midwayjs-tcp
pnpm add @hexys/midwayjs-tcp
yarn add @hexys/midwayjs-tcp
bun add @hexys/midwayjs-tcp
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.5 |
| Published | 2021-09-24 |
| First published | 2021-09-23 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 17.6 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | zhagqn |
| Maintainers | zhagqn |

## Links

- npm: https://www.npmjs.com/package/@hexys/midwayjs-tcp
- npm.io page: https://npm.io/package/@hexys/midwayjs-tcp

## Dependencies (1)

- [@midwayjs/logger](https://npm.io/package/@midwayjs/logger.md) ^2.13.0

## Recent versions

- 0.0.5 (latest) — 2021-09-24
- 0.0.4 — 2021-09-23
- 0.0.3 — 2021-09-23
- 0.0.2 — 2021-09-23
- 0.0.1 — 2021-09-23

## README

# Midway TCP 组件

## 1. 安装

```
npm i @hexys/midwayjs-tcp
```

项目中引用并配置

```typescript
// src/configuration.ts

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

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

## 2. 使用

### 1. 依赖注入

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

### 2. 连接

`TCPClientOptions` 为连接参数配置项

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

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

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

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

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

### 3. 发送消息/关闭连接

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

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

### 4. TCP 事件处理装饰器

连接事件装饰器

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

关闭事件装饰器

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

消息事件装饰器

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

---
_Source: https://npm.io/package/@hexys/midwayjs-tcp · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
