85 lines
2.2 KiB
TypeScript
85 lines
2.2 KiB
TypeScript
|
|
import * as io from "./socket.io.min.js";
|
|
const { ccclass } = cc._decorator;
|
|
const LOGS_SKIPS= [
|
|
'move',
|
|
'balance',
|
|
'update-x-y',
|
|
'gameevent',
|
|
'xmove'
|
|
];
|
|
@ccclass
|
|
export default class SocketIoClient {
|
|
private socket:any = null;
|
|
private static instance: SocketIoClient;
|
|
private _isConnected:boolean = false;
|
|
public set isConnected(val:boolean) {
|
|
this._isConnected = val;
|
|
}
|
|
public get isConnected(){
|
|
return this.socket && this.socket.connected && this._isConnected;
|
|
}
|
|
public async setup() {
|
|
console.log('SocketIoClient setup');
|
|
|
|
}
|
|
|
|
public static getInstance(): SocketIoClient {
|
|
if (this.instance == null) {
|
|
this.instance = new SocketIoClient();
|
|
}
|
|
return this.instance;
|
|
}
|
|
|
|
public connectServer(linkServer:string,auth){
|
|
|
|
console.log("%c"+`connectServer->>>>>: ${linkServer}`, 'color: #bada55');
|
|
if(this.socket){
|
|
this.socket.disconnect();
|
|
}
|
|
if(auth){
|
|
this.socket = io(linkServer, auth);
|
|
}else{
|
|
this.socket = io(linkServer);
|
|
}
|
|
|
|
|
|
}
|
|
|
|
public on(socketEvent:string, callbackData:Function, isOff:boolean = true){
|
|
if(this.socket){
|
|
if(isOff){
|
|
this.socket.off(socketEvent);
|
|
}
|
|
this.socket.on(socketEvent,(msg)=>{
|
|
if(!LOGS_SKIPS.includes(socketEvent)) {
|
|
console.log("%c" + `-->>socket recive: ${socketEvent}: ${JSON.stringify(msg)}`,'color:#ffe000');
|
|
}
|
|
callbackData(msg);
|
|
|
|
});
|
|
}
|
|
}
|
|
|
|
public off(socketEvent:string,listen){
|
|
this.socket && this.socket.off(socketEvent,listen);
|
|
}
|
|
|
|
public emit(socketEvent:string,data?:any){
|
|
if(!LOGS_SKIPS.includes(socketEvent)) {
|
|
console.log("%c"+`-->>socket send: ${socketEvent}: ${JSON.stringify(data)}`,'color:#00ff0c');
|
|
}
|
|
if(!this.isConnected){
|
|
return;
|
|
}
|
|
this.socket && this.socket.emit(socketEvent, data);
|
|
}
|
|
|
|
public close(){
|
|
console.log("%c"+`-->>socket colose:`);
|
|
this.socket && this.socket.disconnect();
|
|
}
|
|
|
|
|
|
}
|