github.com/martinohmann/rfoutlet@v1.2.1-0.20220707195255-8a66aa411105/web/src/websocket.js (about) 1 import WebSocketAsPromised from 'websocket-as-promised'; 2 import config from './config'; 3 4 export class Websocket { 5 defaultListeners = { 6 onOpen: (event) => console.log(`Opened websocket connection`, event), 7 onClose: (event) => console.log(`Closed websocket connection`, event), 8 onError: (event) => console.error(`Websocket error`, event), 9 onMessage: (msg) => console.log("[ws recv]", msg), 10 }; 11 12 constructor(url) { 13 this.ws = new WebSocketAsPromised(url, { 14 packMessage: (data) => JSON.stringify(data), 15 unpackMessage: (message) => JSON.parse(message), 16 }); 17 } 18 19 sendMessage = (data) => this.ws.open() 20 .then(() => { 21 console.log("[ws send]", data); 22 23 this.ws.sendPacked(data); 24 }) 25 .catch(err => console.error(err)); 26 27 onMessage = (cb) => this.ws.onUnpackedMessage.addListener(cb); 28 29 onOpen = (cb) => this.ws.onOpen.addListener(cb); 30 31 onClose = (cb) => this.ws.onClose.addListener(cb); 32 33 onError = (cb) => this.ws.onError.addListener(cb); 34 35 attachDefaultListeners = () => { 36 this.onOpen(this.defaultListeners.onOpen); 37 this.onClose(this.defaultListeners.onClose); 38 this.onError(this.defaultListeners.onError); 39 this.onMessage(this.defaultListeners.onMessage); 40 } 41 } 42 43 const websocket = new Websocket(config.ws.url); 44 45 websocket.attachDefaultListeners(); 46 47 export default websocket;