SHARE
TWEET

Untitled

a guest Jul 23rd, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class SocketManager
  2. {
  3.     constructor()
  4.     {
  5.         this.socket     = null;
  6.         this.didOpen    = false;
  7.     }
  8.  
  9.     connect(url)
  10.     {
  11.         if(this.socket) this.socket.close();
  12.  
  13.         this.didOpen = false;
  14.  
  15.         return new Promise((resolve, reject) =>
  16.         {
  17.             this.socket = new WebSocket(url);
  18.  
  19.             this.socket.onopen = event =>
  20.             {
  21.                 this.didOpen = true;
  22.  
  23.                 resolve();
  24.             }
  25.  
  26.             this.socket.onerror = event =>
  27.             {
  28.                 if(!this.didOpen)
  29.                 {
  30.                     reject();
  31.                 }
  32.                 else
  33.                 {
  34.                     this.onError(event);
  35.                 }
  36.             }
  37.  
  38.             this.socket.onmessage = this.onMessage.bind(this);
  39.             this.socket.onclose = this.onClose.bind(this);
  40.         });
  41.     }
  42.  
  43.     sendMessage(message)
  44.     {
  45.         this.socket.send(message);
  46.     }
  47.  
  48.     onMessage(event)
  49.     {
  50.         // we received a message
  51.         console.log(event);
  52.     }
  53.  
  54.     onClose(event)
  55.     {
  56.         // the socket server closed
  57.         console.log(event);
  58.     }
  59.  
  60.     onError(event)
  61.     {
  62.         // we received some error
  63.         console.log(event);
  64.     }
  65.  
  66.     get socket()
  67.     {
  68.         return this.socket;
  69.     }
  70. }
  71.  
  72.  
  73. // use it like this
  74. const socket = new SocketManager();
  75.  
  76. function connect(url)
  77. {
  78.     socket
  79.         .connect(url)
  80.         .then(() =>
  81.         {
  82.             // the socket was connected, now lets login
  83.             socket.sendMessage('{{ Auth::user()->auth_ticket }}');
  84.  
  85.             // now we can start doing things
  86.         })
  87.         .catch(error =>
  88.         {
  89.             // the socket didnt connect, check the error
  90.             console.log(error);
  91.         });
  92. }
  93.  
  94. connect('ws://');
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top