• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15import socket from '@ohos.net.socket';
16import Logger from '../utils/Logger';
17import Socket from '../model/Socket';
18
19const TAG = 'Socket TcpSocket';
20
21export default class TcpSocket implements Socket {
22  private tcpSocket: socket.TCPSocket | null = null;
23
24  /**
25   * 创建Socket
26   * @param localIp
27   * @param port
28   */
29  async createSocket(localIp: string, port: number): Promise<boolean> {
30    Logger.info(`${TAG} tcp bind localIp: ${localIp}`);
31    try {
32      if (this.tcpSocket) {
33        this.tcpSocket.close();
34        this.tcpSocket = null;
35      }
36
37      this.tcpSocket = socket.constructTCPSocketInstance();
38
39      await this.tcpSocket.bind({
40        address: localIp,
41        port: port,
42        family: 1
43      });
44      Logger.info(`${TAG} tcp bind sucess`);
45      return true;
46    } catch (e) {
47      Logger.error(`${TAG} tcp bind error ${JSON.stringify(e)}}`);
48    }
49    return false;
50  }
51
52  /**
53   * 连接Socket
54   * @param address
55   * @param port
56   */
57  async connectSocket(address: string, port: number): Promise<boolean> {
58    Logger.info(`${TAG} tcp connectSocket address: ${address}`);
59    try {
60      if (!this.tcpSocket) {
61        return false;
62      }
63
64      if (await this.isConnected()) {
65        Logger.info(`${TAG} tcp connectSocket sucess`);
66        return true;
67      }
68      await this.tcpSocket.connect({
69        address: {
70          address: address,
71          port: port,
72          family: 1,
73        },
74        timeout: 6000,
75      });
76      await this.tcpSocket.setExtraOptions({});
77      Logger.info(`${TAG} tcp connectSocket sucess`);
78      return true;
79    } catch (e) {
80      Logger.error(`${TAG} tcp connectSocket error ${JSON.stringify(e)}}`);
81    }
82    return false;
83  }
84
85  /**
86   * 关闭Socket
87   */
88  async closeSocket(): Promise<void> {
89    if (!this.tcpSocket) {
90      return;
91    }
92    await this.tcpSocket.close();
93    this.tcpSocket.off('connect');
94    this.tcpSocket.off('message');
95    this.tcpSocket = null;
96  }
97
98  /**
99   * 发送数据
100   * @param data
101   */
102  async sendData(data: string): Promise<void> {
103    if (!this.tcpSocket) {
104      return;
105    }
106    Logger.info(`${TAG} tcp sendData data ${JSON.stringify(data)}`);
107    try {
108      await this.tcpSocket.send({
109        data: data,
110      });
111    } catch (e) {
112      Logger.error(`${TAG} tcp sendData error ${JSON.stringify(e)}}`);
113    }
114  }
115
116  /**
117   * 判断是否连接
118   */
119  async isConnected(): Promise<boolean> {
120    if (!this.tcpSocket) {
121      return false;
122    }
123
124    try {
125      let state = await this.tcpSocket.getState();
126      if (state.isConnected) {
127        return true;
128      }
129    } catch (e) {
130      Logger.error(`${TAG} tcp getState error ${JSON.stringify(e)}}`);
131    }
132    return false;
133  }
134
135  /**
136   * 订阅消息
137   * @param callback
138   */
139  setOnMessageReceivedListener(callback: (buffer: ArrayBuffer) => void): void {
140    if (!this.tcpSocket) {
141      return;
142    }
143
144    this.tcpSocket.on('message', (data) => {
145      Logger.info(`${TAG} TCP data: ` + JSON.stringify(data));
146      let buffer = data.message;
147      callback(buffer);
148    });
149  }
150
151  /**
152   * TCP 关闭事件订阅
153   * @param callback
154   */
155  setOnCloseListener(callback: () => void): void {
156    Logger.info(`${TAG} TCP setOnCloseListener into`);
157    this.tcpSocket?.on('close', () => {
158      Logger.info(`${TAG} TCP setOnCloseListener onClose:`);
159      callback();
160      this.closeSocket();
161    });
162
163    this.tcpSocket?.on('error', (data) => {
164      Logger.info(
165        `${TAG} TCP setOnCloseListener onClose:` + JSON.stringify(data)
166      );
167      callback();
168      this.closeSocket();
169    });
170  }
171}
172