About WebSocket actually very early want to send, but before the project of the back end of the websocket is not I do, and I want to send to the front and back to discuss with you, and then squeeze out a bit of time to study the back end of the WebSocket implementation (so only this article).
The first is the concept of introduction, now everyone in Baidu, Google can easily search for a lot of such socket (Baidu Encyclopedia), socket detailed (too many are not listed)
After seeing the introduction of these concepts, we are ready to implement the WebSocket service (children's shoes which are not mastered by the basic concepts need to be missed).
When it comes to the websocket implementation of. NET, you have to say SuperSocket, you can click here to learn and download it.
After seeing the link above, you should know that it is a useful tool, and then we can build our Websocketserver:
First, create a form application (WinForm), and of course you can create a console application.
Then, you need to bring the downloaded DLLs into your project: Supersocket.common, Supersocket.socketbase, Supersocket.socketengine, Superwebsocket, Log4net
Where the SuperSocket related class library version for the 1.6,superwebsocket version of 0.9,log4net is 1.2 (version error may be some people who can not read the green chicken).
Next, we need to declare a WebSocket object and bind it to a good event, such as this:
Websocketserver ws = new Websocketserver (); Ws. Newmessagereceived + = ws_newmessagereceived;//When a message is passed in Ws. newsessionconnected + = ws_newsessionconnected;//When a user is connected to Ws. sessionclosed + = ws_sessionclosed;//When a user exits Ws. Newdatareceived + = ws_newdatareceived;//When there is data passing in if (Ws. Setup (10086))//Bind port ws. Start ();//Startup service
Note the annotations should be clear, but I do not have the incoming data to do the operation, you crossing can be ignored.
What should we do next? The answer is to override the generated event method. It's easy to see that we have to deal with the user's connection and exit first, and save and remove the user information (or you don't know who you're talking to), like this:
Dictionary<websocketsession, string> userlist = new dictionary<websocketsession, string> ();//user list
Sharp-eyed's classmates must have found a new type: websocketsession, what does it do? This is the case when F12 in:
Looks like there's nothing? Don't worry, we'll look at it again. Parent class:
Many people here understand that many of the information about connecting users is within this class, and the Send method is provided to communicate with it on the server side.
After figuring out what websocketsession type can do, you can respond to different operations
When the client connects to the server, it needs to send a bunch of messages to tell the server "who I Am", and then it needs to use the Ws_newmessagereceived event method.
For example: When the client is connected, "{' User ': ' No. 001 student ', ' active ': ' Login '}" is sent to the server, then we can store the user's information on the server to the userlist defined above:
Method added to user collection public void AddUser (String UserName, websocketsession session) {Userlist.add (s Ession, UserName); }//login corresponds to package dic method public dictionary<string, string> login (dictionary<string, string> Query, T Curuser) {Userconnhandle Userconn = () = {return query["userid"];}; dictionary<string, string> respon = new dictionary<string, string> (); if (!service.userlist.containskey (Curuser)) {if (query["user"] = = "" | | query["user"] = = null) {Respon.add ("user", Guid.NewGuid (). ToString (). Replace ("-", "")); } else {respon.add ("userid", query["userid"]); } respon.add ("type", "1");//For the front-end easier to manipulate Respon.add ("send", "0");//Here 0 is to tell all users or current users Service. AddUser (respon["user"], curuser);//Add the current user to the user collection } return respon; }//New message is passed in private void Ws_newmessagereceived (websocketsession session, String value) {Dict ionary<string, string> res = login (value, session, this) as Dictionary<string, string>; Switch (res["send"]) {case "0": Res. Remove ("send"); Send (res);//all sends break; Case "1": Res. Remove ("send"); String username = res["to"]; websocketsession keys = userlist. Where (q = = Q.value = = username). Select (q = q.key). First (); SendTo (keys, res);//for Send break; } }
Here I encapsulated dic just for the sake of simple invocation, people are not used to encapsulation into other (such as list<t>), below is send and sendto:
Send to all users public void Send (String msg) { foreach (var item in userlist) { item. Key.send (msg); } } Sent to a single user public void SendTo (websocketsession session, String msg) { session. Send (msg); }
In fact, the public chat is to all the users to do a traversal broadcast, and private chat only need to target a user broadcast.
At this point, the websocketserver based on the SuperSocket implementation has been simply implemented.
This article does not pull out the interface, nor do the IOC (the actual project I did), because it is easier to understand the writing, the structure behind the optimization of the people can play their own ~
About the Web client docking, I will post the article later (not rotten tail!) ) ~ ~
WebSocket (back end) based on the SuperSocket implementation