关注微信公众号:每日玩机 获取ios、Android、tv、mac黑科技软件
新建ts文件写入sockect工具类,具体如下:
class MySockect {
private static _manager: MySockect;
public static get Instance() {
if (MySockect._manager == null) {
MySockect._manager = new MySockect();
}
return MySockect._manager;
}
public constructor() {
}
private socket: egret.WebSocket;
public connectionSockect() {
this.socket = new egret.WebSocket();
this.socket.type = egret.WebSocket.TYPE_STRING;
this.socket.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onReceiveMessage, this);
this.socket.addEventListener(egret.Event.CONNECT, this.onSocketOpen, this);
this.socket.addEventListener(egret.Event.CLOSE, this.onSocketClose, this);
this.socket.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onSocketError, this);
this.socket.connect("192.168.0.8", 3399);
}
public closeSockect() {
this.socket.close();
}
public isConnection() {
return this.socket.connected;
}
public sendData(data): void {
let sendData:string = JSON.stringify(data);
console.log("正在发送数据............");
this.socket.writeUTF(sendData);
console.log("发送数据完成");
}
private onSocketOpen(): void {
console.log("Sockect连接成功");
}
private onSocketClose(): void {
console.log("Sockect连接失败");
}
private onSocketError(): void {
console.log("Sockect连接关闭");
}
public onReceiveMessage() {
let msg = this.socket.readUTF();
let data = JSON.parse(msg);
}
}
工具类的使用方法
- sockect连接
MySockect.Instance.connectionSockect();
- 发送数据
let data = { "path": "test1", "data": { "msg": "test1" } };
MySockect.Instance.sendData(data);
- 其他使用,具体看工具类里的方法…使用MySockect.Instance.调用