Home > front end >  Node. Js implement a simple group chat WebSocket Server
Node. Js implement a simple group chat WebSocket Server

Time:01-07

Do not make private chat function,
Agreement requirements, onopen send:
Ws. Send (JSON. Stringify ({data: {room: "RoomName," Nick, "Nick," icon: "icon"}, type: "join"}));
Then entered the RoomName chat rooms,
 const WS=the require (" WS "). The Server; 
Var chat=new ChatRoom;
New WS ({port: 8080}) on (" connection ", WS=& gt; {
Var user=new ChatUser (ws);
Ws. On (" message ", res=& gt; User. OnMsg (res));
Ws. On (" close ", res=& gt; The user exit (res));
Ws. On (" error ", err=& gt; The console. The log (err));
});
The console. The log (" WebSocket service listening on port 8080 ");

The function ChatRoom () {
This. Join=(user, roomName)=& gt; {
Let room=rooms (roomName) | | {name: roomName, id: 0, the users: the new Object, the count: 0};
if(! Room. Id) rooms [roomName]=room;
. The user id=+ + room. Id; Room. Count++;
The user. The room=room;
Room. The users [user id]=user;
Return the user. The id;
};

This. Kick=user=& gt; {
if(! User. Room) return;
Let room=user. Room;
Room. The count -- --;
Delete the user. The room;
Delete room. Users [user id];
If (room. Count) return;
The delete rooms [room name];
The console. The log (` room ${room. The name} is destroyed `);
};
Var rooms=new Object;
}

The function ChatUser (ws) {
Enclosing onMsg=res=& gt; {
Try {res=JSON. Parse (res); }
The catch (err) {the console. The log (" abnormal data format: "+ res); }
If (res) type=="join") return this. DoJoin (res) data);
Enclosing sendAll (res);
};

This. Send=MSG=& gt; {
If (ws readyState!=1) return the console. The log (" temporarily unable to send, "ws. ReadyState);
Ws. Send (JSON. Stringify (MSG));
};

Enclosing sendAll=MSG=& gt; {
Var room.=this room; if(! Room) return;
For (var x in room. The users) room. Users [x]. Send (MSG);
};

Enclosing the exit ()==& gt; Ws readyState!=3? Ws. The close () : chat. Kick (this);

Enclosing doJoin=data=https://bbs.csdn.net/topics/> {
Data. Id=chat. Join (this, the data room);
This. Send ({type: "join", data: data. The id});
Enclosing sendAll ({type: "welcome," data});
};
}

CodePudding user response:

Thanks for sharing, turn head to test,

CodePudding user response:


Need to install depend on the package?
The first line of error?

CodePudding user response:

NPM install ws.
  • Related