websocket.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import {WEBSOCKET_HOST} from '@/utils/config'
  2. const webSocketService = {
  3. webSocket: null,
  4. init: function(){
  5. this.webSocket = new WebSocket(WEBSOCKET_HOST);
  6. },
  7. onOpen: function(that, callback){
  8. if(this.webSocket === null){
  9. this.init();
  10. }
  11. this.webSocket.onopen = function(evt){
  12. if(typeof callback === 'function'){
  13. callback(evt);
  14. }
  15. };
  16. },
  17. onMessage: function(that, callback){
  18. if(this.webSocket === null){
  19. this.init();
  20. }
  21. this.webSocket.onmessage = function(res){
  22. if(typeof callback === 'function'){
  23. callback(res);
  24. }
  25. }
  26. },
  27. onClose: function(that, callback){
  28. if(this.webSocket === null){
  29. this.init();
  30. }
  31. this.webSocket.onclose = function(evt){
  32. if(typeof callback === 'function'){
  33. callback(evt);
  34. }
  35. };
  36. },
  37. onSend: function (that, data) {
  38. if(this.webSocket === null){
  39. this.init();
  40. }
  41. this.webSocket.send(data);
  42. }
  43. };
  44. webSocketService.init();
  45. export default webSocketService;