chenyc
2024-12-02 c8dde21585f90d052bea1d95f8a5455cac5cc7de
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import net from 'net';
import {fanhuiData2 ,fanhuiState2}from './index'
import logger from '../../utils/logger';
 
 
export default class TcpClient {
  public host: string;
  public port: number;
  /**定时多少毫秒 */
  private retryInterval: number;
  /**客户端连接对象 */
  private client: net.Socket;
 
  public masgData:Buffer;
   
 
  constructor(host: string, port: number) {
    logger.info('新增clientSocket链接对象---'+host)
    this.host = host;
    this.port = port;
    this.client = new net.Socket();
    this.setupClient();
    this.connect();
  }
  
  private setupClient() {
    this.client.on('connect', this.onConnect.bind(this));
    this.client.on('data', this.onData.bind(this));
    this.client.on('close', this.onClose.bind(this));
    this.client.on('error', this.onError.bind(this));
  }
 
  public connect() {
    // 监测连接对象是否存在
    if(this.client){
       // 尝试连接tcp服务
      logger.info(`开始创建链接${this.host}`)
      console.log('Attempting to connect to the TCP server...');
      this.client.connect(this.port, this.host);
    }
   
  }
  
  private onConnect() {
    console.log('Connected to the TCP server');
    logger.info(`创建链接${this.host}成功`)
    // 给ui返回连接状态
    const listData={ip:this.host,data:1}
    fanhuiState2(listData)
    // 向服务器发送消息 
    
  }
  private onData(data: Buffer) {
    console.log(`Received from server: `);
    logger.info(`收到服务端数据${this.host}`) 
    console.log(data)
    fanhuiData2(data)
  }
  
 
  private onClose() {
    const listData={ip:this.host,data:0}
    fanhuiState2(listData)
    console.log('Connection closed by client.');
  }
 
  private onError(err: Error) {
    console.error(`Connection error: ${err.message}`);
    this.client.destroy(); // 销毁当前的 socket 以触发 'close' 事件
  }
 
  public close() {
    console.log('close--client--')
    this.client.end(); 
  }
  public sundData(data:string){
    if(!this.client.destroyed){
        let buffer1 = Buffer.from(data);
        this.client.write(buffer1)
      }else{
        return 
      }
  }
}