Guest User

Untitled

a guest
Mar 22nd, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. function Wss(config){
  2. this.events={};
  3. this.ws = new WebSocket(`${config.host}`);
  4. this.addEvents();
  5. return this;
  6. }
  7.  
  8. Wss.prototype.addEvents=function(){
  9. var context=this;
  10. this.ws.onmessage=function(e){
  11. var data=JSON.parse(e.data)||{};
  12. var type=data.type;
  13. var payload=data.payload;
  14. if (context.events[type]) {
  15. context.events[type].map((event) => {
  16. event.cb(payload);
  17. return this;
  18. });
  19. }
  20. }
  21. }
  22.  
  23. Wss.prototype.on=function(type,fn){
  24. if(!this.events[type]){
  25. this.events[type]=[{
  26. cb:fn
  27. }];
  28. }else{
  29. this.events[type].push({
  30. cb:fn
  31. });
  32. }
  33. }
  34.  
  35. Wss.prototype.send=function(type,payload){
  36. var data=JSON.stringify({
  37. type:type,
  38. payload:payload
  39. });
  40. this.ws.send(data);
  41. }
  42.  
  43. var ws=new Wss({host:'ws://192.168.6.49:8080'});
  44. ws.on('people',function(payload){
  45. console.log('监听到人数发生了变化',payload);
  46. })
Add Comment
Please, Sign In to add comment