Original: ASP. NET SignalR-simple chat room implementation
Simple chat Room
Using the persistent link class we can do some instant messaging applications, I use the Group to do a simple chat room, first technical details below
You can join a chat room, create a chat room, send a message, and tell me how I made it through group.
The persistent link class has a groups object through which we can group add people, send messages, delete people, and so on.
In the connection event, assign a random name to the current visitor and return the currently existing chat room information
protected OverrideTask onconnected (irequest request,stringConnectionID) { varOutPut =NewOutPut {resulttype="roomlist", the Data=roomlist, UserName= $"Visitor {Rdom.next (1, 999)}" }; //return to room information returnconnection.send (ConnectionID, Jsonconvert.serializeobject (OutPut)); }
The following code does the rest of the processing, starting with the creation of the chat room, if the client's request action is Createroom then the current operation is to create a chat room, the chat room ID is a randomly generated GUID, and the current visitors to the current chat room
Joining the chat room is also very simple, using the Groups.add method can be easily done, and then broadcast to the current chat room for everyone to push the new visitors to join
Send the message is the simplest, you can see the last message to send the last parameter ConnectionID, because it is the current person to send messages so that the current people to exclude, to the other people in the chat room to send
protected OverrideTask onreceived (irequest request,stringConnectionID,stringdata) { varDTO = jsonconvert.deserializeobject<groupdto>(data); varOutPut =NewOutPut {resulttype="Msgresult", the Data= $"{dto. UserName}: {dto. Data}", Currentroomid=DTOs. Roomid}; if(DTO.) Action.equals ("Jionus")) { //Join the chat roomGroups.add (ConnectionID, Dto. ROOMID); Output.data= $"Welcome {Dto. UserName} join {dto. Roomname} chat Room"; Output.currentroomid=DTOs. Roomid; Connection.send (ConnectionID, Jsonconvert.serializeobject (OutPut)); returnGroups.send (dto. Roomid, Jsonconvert.serializeobject (OutPut)); } if(DTO.) Action.equals ("Createroom")) { //Create a chat room varhostel =NewGroup () {roomid = Guid.NewGuid (). ToString (), Roomname =DTOs. Roomname}; Groups.add (ConnectionID, the. ROOMID); Dto. Roomid=. Roomid; Roomlist.add (guest); //back to the chat room listOutput.resulttype ="roomlist"; Output.data=roomlist; Output.currentroomid=DTOs. Roomid; //Send Message returnconnection.send (ConnectionID, Jsonconvert.serializeobject (OutPut)); } //Send Message returnGroups.send (dto. Roomid, Jsonconvert.serializeobject (OutPut), ConnectionID); }
ASP. NET SignalR-simple chat room implementation