ts-communication 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +246 -14
  3. package/dist/Invt/InvtModbusTcp.d.ts +88 -0
  4. package/dist/Invt/InvtModbusTcp.js +255 -0
  5. package/dist/XCommunication.d.ts +18 -0
  6. package/dist/XCommunication.js +29 -0
  7. package/dist/ab/AbEtherNetIp.d.ts +1 -0
  8. package/dist/ab/AbEtherNetIp.js +2 -0
  9. package/dist/core/CommunicationLock.d.ts +88 -0
  10. package/dist/core/CommunicationLock.js +156 -0
  11. package/dist/core/Core.d.ts +27 -1
  12. package/dist/core/Core.js +375 -71
  13. package/dist/core/DeviceSerialPort.d.ts +64 -0
  14. package/dist/core/DeviceSerialPort.js +283 -0
  15. package/dist/core/DeviceUdpNet.d.ts +56 -0
  16. package/dist/core/DeviceUdpNet.js +307 -0
  17. package/dist/core/INetMessage.d.ts +145 -0
  18. package/dist/core/INetMessage.js +240 -0
  19. package/dist/debug/PingTest.d.ts +11 -0
  20. package/dist/debug/PingTest.js +59 -0
  21. package/dist/debug/tcpClient.d.ts +11 -0
  22. package/dist/debug/tcpClient.js +116 -0
  23. package/dist/debug/tcpServer.d.ts +12 -0
  24. package/dist/debug/tcpServer.js +102 -0
  25. package/dist/delta/DeltaTcpNet.d.ts +65 -0
  26. package/dist/delta/DeltaTcpNet.js +346 -0
  27. package/dist/ge/GeSRTPNet.d.ts +49 -0
  28. package/dist/ge/GeSRTPNet.js +337 -0
  29. package/dist/inovance/InovanceEasyNet.d.ts +8 -0
  30. package/dist/inovance/InovanceEasyNet.js +103 -0
  31. package/dist/inovance/InovanceSerial.d.ts +55 -0
  32. package/dist/inovance/InovanceSerial.js +145 -0
  33. package/dist/inovance/InovanceSerialOverTcp.d.ts +39 -0
  34. package/dist/inovance/InovanceSerialOverTcp.js +172 -0
  35. package/dist/inovance/InovanceTcpNet.d.ts +2 -4
  36. package/dist/inovance/InovanceTcpNet.js +40 -13
  37. package/dist/melsec/MelsecMcAsciiNet.d.ts +49 -0
  38. package/dist/melsec/MelsecMcAsciiNet.js +196 -0
  39. package/dist/melsec/MelsecMcAsciiUdp.d.ts +54 -0
  40. package/dist/melsec/MelsecMcAsciiUdp.js +204 -0
  41. package/dist/melsec/MelsecMcNet.d.ts +1 -8
  42. package/dist/melsec/MelsecMcNet.js +4 -14
  43. package/dist/melsec/MelsecMcUdp.d.ts +52 -0
  44. package/dist/melsec/MelsecMcUdp.js +191 -0
  45. package/dist/modbus/ModbusAscii.d.ts +24 -3
  46. package/dist/modbus/ModbusAscii.js +109 -3
  47. package/dist/modbus/ModbusAsciiOverTcp.d.ts +21 -3
  48. package/dist/modbus/ModbusAsciiOverTcp.js +67 -3
  49. package/dist/modbus/ModbusRtu.d.ts +101 -13
  50. package/dist/modbus/ModbusRtu.js +355 -21
  51. package/dist/modbus/ModbusRtuOverTcp.d.ts +23 -3
  52. package/dist/modbus/ModbusRtuOverTcp.js +68 -3
  53. package/dist/modbus/ModbusTcpNet.d.ts +16 -3
  54. package/dist/modbus/ModbusTcpNet.js +192 -60
  55. package/dist/modbus/ModbusUdpNet.d.ts +26 -3
  56. package/dist/modbus/ModbusUdpNet.js +125 -2
  57. package/dist/omron/OmronFinsNet.d.ts +1 -2
  58. package/dist/omron/OmronFinsNet.js +210 -69
  59. package/dist/omron/OmronFinsUdp.d.ts +41 -0
  60. package/dist/omron/OmronFinsUdp.js +146 -0
  61. package/dist/siemens/SiemensS7Net.d.ts +6 -0
  62. package/dist/siemens/SiemensS7Net.js +45 -6
  63. package/dist/xinjie/XinJETcpNet.d.ts +18 -0
  64. package/dist/xinjie/XinJETcpNet.js +106 -0
  65. package/package.json +16 -3
@@ -0,0 +1,145 @@
1
+ /**
2
+ * 本系统的消息类,包含了各种解析规则,数据信息提取规则
3
+ * The message class of this system contains various parsing rules and data information extraction rules
4
+ */
5
+ export interface INetMessage {
6
+ /**
7
+ * 消息头的指令长度,第一次接受数据的长度
8
+ * Instruction length of the message header, the length of the first received data
9
+ */
10
+ ProtocolHeadBytesLength: number;
11
+ /**
12
+ * 消息头字节
13
+ * Message header byte
14
+ */
15
+ HeadBytes: Buffer;
16
+ /**
17
+ * 消息内容字节
18
+ * Message content byte
19
+ */
20
+ ContentBytes: Buffer;
21
+ /**
22
+ * 发送的字节信息
23
+ * Byte information sent
24
+ */
25
+ SendBytes: Buffer;
26
+ /**
27
+ * 从当前的头子节文件中提取出接下来需要接收的数据长度
28
+ * Extract the length of the data to be received from the current header file
29
+ * @returns 返回接下来的数据内容长度,如果小于0表示头部未接收完整
30
+ */
31
+ GetContentLengthByHeadBytes(): number;
32
+ /**
33
+ * 在接收头报文的时候,返回前置无效的报文头字节长度,默认为0,不处理
34
+ * When receiving a header message, return the header byte length of the invalid header, the default is 0, and no processing is performed.
35
+ * @param headByte 接收到的头子节信息
36
+ * @returns 头子节中无效的字节长度信息
37
+ */
38
+ PependedUselesByteLength(headByte: Buffer): number;
39
+ /**
40
+ * 检查头子节的合法性
41
+ * Check the legitimacy of the head subsection
42
+ * @param token 特殊的令牌,有些特殊消息的验证
43
+ * @returns 是否合法
44
+ */
45
+ CheckHeadBytesLegal(token?: Buffer): boolean;
46
+ /**
47
+ * 获取头子节里的消息标识
48
+ * Get the message ID in the header subsection
49
+ * @returns 消息标识
50
+ */
51
+ GetHeadBytesIdentity(): number;
52
+ /**
53
+ * 检查发送的接收的报文是否是匹配的
54
+ * Check if the sent and received messages match
55
+ * @param send 当前发送的报文
56
+ * @param receive 当前接收的报文信息
57
+ * @returns 如果匹配返回 1,如果不匹配且直接返回错误返回 0,如果不匹配继续接收返回 -1
58
+ */
59
+ CheckMessageMatch(send: Buffer, receive: Buffer): number;
60
+ }
61
+ /**
62
+ * 消息基类
63
+ */
64
+ export declare abstract class NetMessageBase implements INetMessage {
65
+ ProtocolHeadBytesLength: number;
66
+ HeadBytes: Buffer;
67
+ ContentBytes: Buffer;
68
+ SendBytes: Buffer;
69
+ abstract GetContentLengthByHeadBytes(): number;
70
+ PependedUselesByteLength(headByte: Buffer): number;
71
+ CheckHeadBytesLegal(token?: Buffer): boolean;
72
+ GetHeadBytesIdentity(): number;
73
+ CheckMessageMatch(send: Buffer, receive: Buffer): number;
74
+ }
75
+ /**
76
+ * Modbus TCP 消息
77
+ */
78
+ export declare class ModbusTcpMessage extends NetMessageBase {
79
+ ProtocolHeadBytesLength: number;
80
+ private isCheckMessageId;
81
+ constructor(isCheckMessageId?: boolean);
82
+ GetContentLengthByHeadBytes(): number;
83
+ CheckHeadBytesLegal(token?: Buffer): boolean;
84
+ GetHeadBytesIdentity(): number;
85
+ CheckMessageMatch(send: Buffer, receive: Buffer): number;
86
+ }
87
+ /**
88
+ * Modbus RTU 消息
89
+ */
90
+ export declare class ModbusRtuMessage extends NetMessageBase {
91
+ ProtocolHeadBytesLength: number;
92
+ private stationCheckMatch;
93
+ constructor(stationCheckMatch?: boolean);
94
+ GetContentLengthByHeadBytes(): number;
95
+ CheckHeadBytesLegal(token?: Buffer): boolean;
96
+ CheckMessageMatch(send: Buffer, receive: Buffer): number;
97
+ }
98
+ /**
99
+ * Modbus ASCII 消息
100
+ */
101
+ export declare class ModbusAsciiMessage extends NetMessageBase {
102
+ ProtocolHeadBytesLength: number;
103
+ GetContentLengthByHeadBytes(): number;
104
+ CheckHeadBytesLegal(token?: Buffer): boolean;
105
+ PependedUselesByteLength(headByte: Buffer): number;
106
+ }
107
+ /**
108
+ * Siemens S7 消息
109
+ */
110
+ export declare class S7Message extends NetMessageBase {
111
+ ProtocolHeadBytesLength: number;
112
+ GetContentLengthByHeadBytes(): number;
113
+ CheckHeadBytesLegal(token?: Buffer): boolean;
114
+ }
115
+ /**
116
+ * Omron FINS 消息
117
+ */
118
+ export declare class FinsMessage extends NetMessageBase {
119
+ ProtocolHeadBytesLength: number;
120
+ GetContentLengthByHeadBytes(): number;
121
+ CheckHeadBytesLegal(token?: Buffer): boolean;
122
+ }
123
+ /**
124
+ * Omron FINS UDP 消息
125
+ */
126
+ export declare class FinsUdpMessage extends NetMessageBase {
127
+ ProtocolHeadBytesLength: number;
128
+ GetContentLengthByHeadBytes(): number;
129
+ CheckHeadBytesLegal(token?: Buffer): boolean;
130
+ }
131
+ /**
132
+ * Melsec MC 消息
133
+ */
134
+ export declare class MelsecMcMessage extends NetMessageBase {
135
+ ProtocolHeadBytesLength: number;
136
+ GetContentLengthByHeadBytes(): number;
137
+ CheckHeadBytesLegal(token?: Buffer): boolean;
138
+ }
139
+ /** 通用电气 SRTP 消息,头部固定为 56 字节,长度字段采用小端序。 */
140
+ export declare class GeSRTPMessage extends NetMessageBase {
141
+ ProtocolHeadBytesLength: number;
142
+ GetContentLengthByHeadBytes(): number;
143
+ CheckHeadBytesLegal(): boolean;
144
+ CheckMessageMatch(send: Buffer, receive: Buffer): number;
145
+ }
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GeSRTPMessage = exports.MelsecMcMessage = exports.FinsUdpMessage = exports.FinsMessage = exports.S7Message = exports.ModbusAsciiMessage = exports.ModbusRtuMessage = exports.ModbusTcpMessage = exports.NetMessageBase = void 0;
4
+ /**
5
+ * 消息基类
6
+ */
7
+ class NetMessageBase {
8
+ ProtocolHeadBytesLength = 0;
9
+ HeadBytes = Buffer.alloc(0);
10
+ ContentBytes = Buffer.alloc(0);
11
+ SendBytes = Buffer.alloc(0);
12
+ PependedUselesByteLength(headByte) {
13
+ return 0;
14
+ }
15
+ CheckHeadBytesLegal(token) {
16
+ return true;
17
+ }
18
+ GetHeadBytesIdentity() {
19
+ return 0;
20
+ }
21
+ CheckMessageMatch(send, receive) {
22
+ return 1; // 默认匹配
23
+ }
24
+ }
25
+ exports.NetMessageBase = NetMessageBase;
26
+ /**
27
+ * Modbus TCP 消息
28
+ */
29
+ class ModbusTcpMessage extends NetMessageBase {
30
+ ProtocolHeadBytesLength = 6;
31
+ isCheckMessageId = true;
32
+ constructor(isCheckMessageId = true) {
33
+ super();
34
+ this.isCheckMessageId = isCheckMessageId;
35
+ }
36
+ GetContentLengthByHeadBytes() {
37
+ if (this.HeadBytes.length < 6)
38
+ return -1;
39
+ return this.HeadBytes.readUInt16BE(4) - 1;
40
+ }
41
+ CheckHeadBytesLegal(token) {
42
+ if (this.HeadBytes.length < 6)
43
+ return false;
44
+ // 检查协议标识符是否为 0
45
+ return this.HeadBytes.readUInt16BE(2) === 0;
46
+ }
47
+ GetHeadBytesIdentity() {
48
+ if (this.HeadBytes.length < 2)
49
+ return 0;
50
+ return this.HeadBytes.readUInt16BE(0);
51
+ }
52
+ CheckMessageMatch(send, receive) {
53
+ if (!this.isCheckMessageId)
54
+ return 1;
55
+ if (send.length < 2 || receive.length < 2)
56
+ return -1;
57
+ const sendId = send.readUInt16BE(0);
58
+ const receiveId = receive.readUInt16BE(0);
59
+ return sendId === receiveId ? 1 : -1;
60
+ }
61
+ }
62
+ exports.ModbusTcpMessage = ModbusTcpMessage;
63
+ /**
64
+ * Modbus RTU 消息
65
+ */
66
+ class ModbusRtuMessage extends NetMessageBase {
67
+ ProtocolHeadBytesLength = 3;
68
+ stationCheckMatch = true;
69
+ constructor(stationCheckMatch = true) {
70
+ super();
71
+ this.stationCheckMatch = stationCheckMatch;
72
+ }
73
+ GetContentLengthByHeadBytes() {
74
+ if (this.HeadBytes.length < 3)
75
+ return -1;
76
+ const functionCode = this.HeadBytes[1];
77
+ // 异常响应
78
+ if ((functionCode & 0x80) !== 0) {
79
+ return 3; // 站号 + 功能码 + 异常码 + CRC(2)
80
+ }
81
+ // 根据功能码判断长度
82
+ if (functionCode === 0x01 || functionCode === 0x02 || functionCode === 0x03 || functionCode === 0x04) {
83
+ // 读取响应:站号 + 功能码 + 字节数 + 数据 + CRC
84
+ return this.HeadBytes[2] + 2; // 字节数 + CRC
85
+ }
86
+ else if (functionCode === 0x05 || functionCode === 0x06 || functionCode === 0x0F || functionCode === 0x10) {
87
+ // 写入响应:站号 + 功能码 + 地址(2) + 数量(2) + CRC(2)
88
+ return 5; // 4字节数据 + 2字节CRC
89
+ }
90
+ else if (functionCode === 0x16) {
91
+ // 掩码写寄存器
92
+ return 5;
93
+ }
94
+ else if (functionCode === 0x17) {
95
+ // 读写寄存器
96
+ return this.HeadBytes[2] + 2;
97
+ }
98
+ return -1;
99
+ }
100
+ CheckHeadBytesLegal(token) {
101
+ if (this.HeadBytes.length < 1)
102
+ return false;
103
+ // 站号应该在 0-247 之间
104
+ return this.HeadBytes[0] >= 0 && this.HeadBytes[0] <= 247;
105
+ }
106
+ CheckMessageMatch(send, receive) {
107
+ if (!this.stationCheckMatch)
108
+ return 1;
109
+ if (send.length < 1 || receive.length < 1)
110
+ return -1;
111
+ // 检查站号是否匹配
112
+ return send[0] === receive[0] ? 1 : 0;
113
+ }
114
+ }
115
+ exports.ModbusRtuMessage = ModbusRtuMessage;
116
+ /**
117
+ * Modbus ASCII 消息
118
+ */
119
+ class ModbusAsciiMessage extends NetMessageBase {
120
+ ProtocolHeadBytesLength = -1; // 动态长度,以 \r\n 结尾
121
+ GetContentLengthByHeadBytes() {
122
+ // ASCII 模式下,消息以 ':' 开头,'\r\n' 结尾
123
+ // 在接收完整消息前返回 -1
124
+ return -1;
125
+ }
126
+ CheckHeadBytesLegal(token) {
127
+ if (this.HeadBytes.length < 1)
128
+ return false;
129
+ // 必须以 ':' 开头
130
+ return this.HeadBytes[0] === 0x3A; // ':'
131
+ }
132
+ PependedUselesByteLength(headByte) {
133
+ // 跳过开头的无效字符,直到遇到 ':'
134
+ for (let i = 0; i < headByte.length; i++) {
135
+ if (headByte[i] === 0x3A)
136
+ return i; // ':'
137
+ }
138
+ return 0;
139
+ }
140
+ }
141
+ exports.ModbusAsciiMessage = ModbusAsciiMessage;
142
+ /**
143
+ * Siemens S7 消息
144
+ */
145
+ class S7Message extends NetMessageBase {
146
+ ProtocolHeadBytesLength = 4; // TPKT 头部
147
+ GetContentLengthByHeadBytes() {
148
+ if (this.HeadBytes.length < 4)
149
+ return -1;
150
+ // TPKT 格式:版本(1) + 保留(1) + 长度(2)
151
+ if (this.HeadBytes[0] !== 0x03)
152
+ return -1; // 版本必须是 3
153
+ const totalLength = this.HeadBytes.readUInt16BE(2);
154
+ return totalLength - 4; // 减去头部长度
155
+ }
156
+ CheckHeadBytesLegal(token) {
157
+ if (this.HeadBytes.length < 1)
158
+ return false;
159
+ // 检查 TPKT 版本号
160
+ return this.HeadBytes[0] === 0x03;
161
+ }
162
+ }
163
+ exports.S7Message = S7Message;
164
+ /**
165
+ * Omron FINS 消息
166
+ */
167
+ class FinsMessage extends NetMessageBase {
168
+ ProtocolHeadBytesLength = 8; // FINS/TCP 头部
169
+ GetContentLengthByHeadBytes() {
170
+ if (this.HeadBytes.length < 8)
171
+ return -1;
172
+ // FINS/TCP 格式:'FINS'(4) + 长度(4)
173
+ if (this.HeadBytes.toString('ascii', 0, 4) !== 'FINS')
174
+ return -1;
175
+ const length = this.HeadBytes.readUInt32BE(4);
176
+ return length - 8; // 减去头部长度
177
+ }
178
+ CheckHeadBytesLegal(token) {
179
+ if (this.HeadBytes.length < 4)
180
+ return false;
181
+ // 检查 FINS 标识
182
+ return this.HeadBytes.toString('ascii', 0, 4) === 'FINS';
183
+ }
184
+ }
185
+ exports.FinsMessage = FinsMessage;
186
+ /**
187
+ * Omron FINS UDP 消息
188
+ */
189
+ class FinsUdpMessage extends NetMessageBase {
190
+ ProtocolHeadBytesLength = 10; // FINS UDP 头部
191
+ GetContentLengthByHeadBytes() {
192
+ if (this.HeadBytes.length < 10)
193
+ return -1;
194
+ // UDP 模式下,剩余长度由数据包总长度决定
195
+ // 这里返回一个足够大的值,实际长度由 UDP 数据包决定
196
+ return 2000;
197
+ }
198
+ CheckHeadBytesLegal(token) {
199
+ return true; // UDP 模式下不检查头部
200
+ }
201
+ }
202
+ exports.FinsUdpMessage = FinsUdpMessage;
203
+ /**
204
+ * Melsec MC 消息
205
+ */
206
+ class MelsecMcMessage extends NetMessageBase {
207
+ ProtocolHeadBytesLength = 11; // MC 协议头部
208
+ GetContentLengthByHeadBytes() {
209
+ if (this.HeadBytes.length < 11)
210
+ return -1;
211
+ // MC 二进制格式:副头部(2) + 网络号(1) + PC号(1) + 目标模块I/O号(2) + 目标站号(1) + 请求数据长度(2) + 监视定时器(2)
212
+ const dataLength = this.HeadBytes.readUInt16LE(7);
213
+ return dataLength - 2; // 减去监视定时器长度
214
+ }
215
+ CheckHeadBytesLegal(token) {
216
+ if (this.HeadBytes.length < 2)
217
+ return false;
218
+ // 检查副头部(二进制:0x5000,ASCII:0x3530 0x3030)
219
+ return this.HeadBytes.readUInt16LE(0) === 0x5000 || this.HeadBytes.readUInt16BE(0) === 0x3530;
220
+ }
221
+ }
222
+ exports.MelsecMcMessage = MelsecMcMessage;
223
+ /** 通用电气 SRTP 消息,头部固定为 56 字节,长度字段采用小端序。 */
224
+ class GeSRTPMessage extends NetMessageBase {
225
+ ProtocolHeadBytesLength = 56;
226
+ GetContentLengthByHeadBytes() {
227
+ if (this.HeadBytes.length < 56)
228
+ return -1;
229
+ return this.HeadBytes[4] | (this.HeadBytes[5] << 8);
230
+ }
231
+ CheckHeadBytesLegal() {
232
+ return this.HeadBytes.length >= 2 && (this.HeadBytes[0] === 1 || this.HeadBytes[0] === 2 || this.HeadBytes[0] === 3);
233
+ }
234
+ CheckMessageMatch(send, receive) {
235
+ if (send.length < 4 || receive.length < 4)
236
+ return -1;
237
+ return send[2] === receive[2] && send[3] === receive[3] ? 1 : -1;
238
+ }
239
+ }
240
+ exports.GeSRTPMessage = GeSRTPMessage;
@@ -0,0 +1,11 @@
1
+ export interface PingResult {
2
+ success: boolean;
3
+ host: string;
4
+ time?: number;
5
+ message: string;
6
+ }
7
+ export declare class PingTest {
8
+ static ping(host: string, timeout?: number, count?: number): Promise<PingResult>;
9
+ private static parsePingOutput;
10
+ static isHostOnline(host: string, timeout?: number): Promise<boolean>;
11
+ }
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PingTest = void 0;
4
+ const node_child_process_1 = require("node:child_process");
5
+ const node_util_1 = require("node:util");
6
+ const execAsync = (0, node_util_1.promisify)(node_child_process_1.exec);
7
+ class PingTest {
8
+ static async ping(host, timeout = 5000, count = 4) {
9
+ try {
10
+ const isWindows = process.platform === 'win32';
11
+ let command;
12
+ if (isWindows) {
13
+ command = 'ping -n ' + count + ' -w ' + timeout + ' ' + host;
14
+ }
15
+ else {
16
+ const timeoutSec = Math.ceil(timeout / 1000);
17
+ command = 'ping -c ' + count + ' -W ' + timeoutSec + ' ' + host;
18
+ }
19
+ console.log('[PingTest] Executing: ' + command);
20
+ const { stdout, stderr } = await execAsync(command);
21
+ if (stderr) {
22
+ return { success: false, host, message: stderr };
23
+ }
24
+ return PingTest.parsePingOutput(stdout, host, isWindows);
25
+ }
26
+ catch (error) {
27
+ const err = error;
28
+ return { success: false, host, message: err.message };
29
+ }
30
+ }
31
+ static parsePingOutput(output, host, isWindows) {
32
+ const hasReply = output.includes('bytes from') || output.includes('来自');
33
+ if (!hasReply) {
34
+ return { success: false, host, message: 'Host unreachable or timeout' };
35
+ }
36
+ let avgTime;
37
+ if (isWindows) {
38
+ const match = output.match(/平均\s*=\s*(\d+)ms|Average\s*=\s*(\d+)ms/i);
39
+ if (match)
40
+ avgTime = parseInt(match[1] || match[2]);
41
+ }
42
+ else {
43
+ const match = output.match(/rtt\s+min\/avg\/max\/mdev\s+=\s+[\d.]+\/([\d.]+)\//);
44
+ if (match)
45
+ avgTime = parseFloat(match[1]);
46
+ }
47
+ return {
48
+ success: true,
49
+ host,
50
+ time: avgTime,
51
+ message: avgTime !== undefined ? 'Average: ' + avgTime + 'ms' : 'Success'
52
+ };
53
+ }
54
+ static async isHostOnline(host, timeout = 2000) {
55
+ const result = await PingTest.ping(host, timeout, 1);
56
+ return result.success;
57
+ }
58
+ }
59
+ exports.PingTest = PingTest;
@@ -0,0 +1,11 @@
1
+ export declare class TcpClient {
2
+ private socket?;
3
+ host: string;
4
+ port: number;
5
+ timeout: number;
6
+ constructor(host?: string, port?: number);
7
+ connect(): Promise<boolean>;
8
+ send(data: Buffer): Promise<boolean>;
9
+ sendAndReceive(data: Buffer, receiveTimeout?: number): Promise<Buffer | null>;
10
+ disconnect(): void;
11
+ }
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.TcpClient = void 0;
37
+ const net = __importStar(require("node:net"));
38
+ class TcpClient {
39
+ socket;
40
+ host;
41
+ port;
42
+ timeout = 5000;
43
+ constructor(host = '127.0.0.1', port = 5000) {
44
+ this.host = host;
45
+ this.port = port;
46
+ }
47
+ async connect() {
48
+ return new Promise((resolve) => {
49
+ this.socket = new net.Socket();
50
+ const timer = setTimeout(() => {
51
+ this.socket?.destroy();
52
+ console.log('[TcpClient] Connection timeout');
53
+ resolve(false);
54
+ }, this.timeout);
55
+ this.socket.connect(this.port, this.host, () => {
56
+ clearTimeout(timer);
57
+ console.log('[TcpClient] Connected to ' + this.host + ':' + this.port);
58
+ resolve(true);
59
+ });
60
+ this.socket.on('error', (err) => {
61
+ clearTimeout(timer);
62
+ console.error('[TcpClient] Error:', err.message);
63
+ resolve(false);
64
+ });
65
+ });
66
+ }
67
+ async send(data) {
68
+ if (!this.socket || this.socket.destroyed) {
69
+ console.error('[TcpClient] Socket not connected');
70
+ return false;
71
+ }
72
+ return new Promise((resolve) => {
73
+ this.socket.write(data, (err) => {
74
+ if (err) {
75
+ console.error('[TcpClient] Send error:', err.message);
76
+ resolve(false);
77
+ }
78
+ else {
79
+ console.log('[TcpClient] Sent ' + data.length + ' bytes:', data.toString('hex'));
80
+ resolve(true);
81
+ }
82
+ });
83
+ });
84
+ }
85
+ async sendAndReceive(data, receiveTimeout = 5000) {
86
+ if (!this.socket || this.socket.destroyed)
87
+ return null;
88
+ return new Promise((resolve) => {
89
+ let received = Buffer.alloc(0);
90
+ let done = false;
91
+ const finish = (result) => {
92
+ if (done)
93
+ return;
94
+ done = true;
95
+ clearTimeout(timer);
96
+ this.socket.removeListener('data', onData);
97
+ resolve(result);
98
+ };
99
+ const onData = (chunk) => {
100
+ received = Buffer.concat([received, chunk]);
101
+ console.log('[TcpClient] Received ' + chunk.length + ' bytes');
102
+ };
103
+ const timer = setTimeout(() => finish(received.length > 0 ? received : null), receiveTimeout);
104
+ this.socket.on('data', onData);
105
+ this.socket.write(data);
106
+ });
107
+ }
108
+ disconnect() {
109
+ if (this.socket) {
110
+ this.socket.destroy();
111
+ this.socket = undefined;
112
+ console.log('[TcpClient] Disconnected');
113
+ }
114
+ }
115
+ }
116
+ exports.TcpClient = TcpClient;
@@ -0,0 +1,12 @@
1
+ export declare class TcpServer {
2
+ private server?;
3
+ private clients;
4
+ port: number;
5
+ host: string;
6
+ constructor(port?: number, host?: string);
7
+ start(): Promise<boolean>;
8
+ private handleConnection;
9
+ broadcast(data: Buffer): void;
10
+ getClientCount(): number;
11
+ stop(): Promise<void>;
12
+ }