GameNet.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. export default class GameNet{
  2. private static instance: GameNet = null;
  3. private ws: WebSocket = null;
  4. private constructor(){}
  5. public static getInstance(): GameNet{
  6. if(GameNet.instance === null){
  7. GameNet.instance = new GameNet();
  8. }
  9. return GameNet.instance;
  10. }
  11. public init(id, callback: Function, target: any){
  12. if(this.ws != null)return;
  13. // https://www.yuyekeji.cn/api_dapp/index 192.168.0.106:26001
  14. // wss://www.yuyekeji.cn/api_dapp/websocket/dappBack/
  15. this.ws = new WebSocket(window['dappWss']+id);
  16. this.ws.onopen = (event: Event)=>{
  17. callback.call(target, "登录成功");
  18. }
  19. this.ws.onmessage = (event: MessageEvent)=>{
  20. callback.call(target, event.data);
  21. }
  22. this.ws.onerror = function (e) {
  23. console.error("WebSocket连接发生错误");
  24. };
  25. }
  26. public sendMsg(data: string){
  27. if(this.ws != null && this.ws.readyState != WebSocket.OPEN)return;
  28. this.ws.send(data);
  29. }
  30. }