Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Wss(config){
- this.events={};
- this.ws = new WebSocket(`${config.host}`);
- this.addEvents();
- return this;
- }
- Wss.prototype.addEvents=function(){
- var context=this;
- this.ws.onmessage=function(e){
- var data=JSON.parse(e.data)||{};
- var type=data.type;
- var payload=data.payload;
- if (context.events[type]) {
- context.events[type].map((event) => {
- event.cb(payload);
- return this;
- });
- }
- }
- }
- Wss.prototype.on=function(type,fn){
- if(!this.events[type]){
- this.events[type]=[{
- cb:fn
- }];
- }else{
- this.events[type].push({
- cb:fn
- });
- }
- }
- Wss.prototype.send=function(type,payload){
- var data=JSON.stringify({
- type:type,
- payload:payload
- });
- this.ws.send(data);
- }
- var ws=new Wss({host:'ws://192.168.6.49:8080'});
- ws.on('people',function(payload){
- console.log('监听到人数发生了变化',payload);
- })
Add Comment
Please, Sign In to add comment