Advertisement
KoctrX

Untitled

Oct 6th, 2023
869
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const socket = new class {
  2.     constructor() {
  3.         this.socketURI = '';
  4.         this.connect();
  5.     }
  6.  
  7.     connect() {
  8.         this.ws = new WebSocket(this.socketURI);
  9.  
  10.         this.ws.onopen = event => this.onopen(event);
  11.         this.ws.onclose = event => this.onclose(event);
  12.         this.ws.onerror = event => this.onerror(event);
  13.         this.ws.onmessage = event => this.onmessage(event);
  14.     }
  15.  
  16.     onmessage(ev) {
  17.         const data = JSON.parse(ev.data);
  18.  
  19.         switch(data.event) {
  20.             // handle
  21.         }
  22.     }
  23.  
  24.     onopen() {
  25.         console.log('Socket connected');
  26.     }
  27.    
  28.     onclose() {
  29.         console.log('Socket closed');
  30.         setTimeout(() => this.connect(), 2000);
  31.     }
  32.  
  33.     onerror(error) {
  34.         console.log('Socket error: ', error);
  35.     }
  36. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement