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
|
}
|
}
|
}
|