Step by Step Learning WebSocket (ii) using Superwebsocket to achieve their own service side

Source: Internet
Author: User
Tags processing text

In the previous article, we learned how the client creates a WebSocket connection to the server. But a slap does not sound, since it is communication, it is necessary to have at least two end. Today we look at how C # implements a WebSocket server with an existing framework.

In the. Net Framework 4.5 and later, Microsoft has integrated the basic implementation of the WebSocket protocol for us. The WebSocket object provided by Microsoft is located under the System.Net.WebSocket namespace and is cumbersome to use, so I chose the superwebsocket framework to make it easier to develop.

The Superwebsocket framework can be directly obtained and referenced to the project through NuGet, or the latest DLL can be downloaded in http://superwebsocket.codeplex.com/

Let's see Superwebsocket how we can quickly build a server

  

Websocketserver WSServer =NewWebsocketserver (); if(!wsserver.setup ("127.0.0.1", -))            {                //setting IP and port failures is usually caused by IP and port range IPV4 IPV6            }            if(!Wsserver.start ()) {                //Open service failure is basically the port is occupied or blocked by an anti-virus software caused by                return; } wsserver.newsessionconnected+ = (Session) =            {                //There is a new connection            }; Wsserver.sessionclosed+ = (session, reason) =            {                //There is a disconnected connection            }; Wsserver.newmessagereceived+ = (session, message) = =            {                //receive a new text message            }; Wsserver.newdatareceived+ = (Session, bytes) =            {                //receive new binary messages            };            Console.readkey (); Wsserver.stop ();
View Code

Here the Websocketserver object is set by Setup for the IP and port to listen on. Then use the Start method to start listening.

The Setup method has 4 overloads, but we usually use only set IP and port, IP is string, and if the incoming string cannot be converted to the supported IP format, the Setup method returns false to indicate that the setting failed.

Websocketserver also provides 4 events to manage connections to clients, disconnects, and accepts message actions. The new version of WebSocket supports the transfer of data formats with both "text" and "binary", newmessagereceived events for processing text-type messages, and newdatareceived events for processing binary types of messages.

  

Here we have successfully built a service that implements the WebSocket protocol. There are many ways to host a server, and the Superwebsocket framework supports hosting services in the form of consoles, Winform, IIS, and Windows services, although many of the information on the web is not recommended for boarding in IIS, which is said to be relatively low performance in IIS.

WebSocket since it is a duplex communication, then we can not wait to receive messages from the client, we also need to "push" the message from the server side to the client, now we see how to send a message to the client by the server.

In the Superwebsocket framework, the client-side Connection object created by the server is the websocketsession type, which means that it treats each client instance as a single session, generating the session when the client creates the connection, and when the client disconnects, This session is destroyed, and the client communicates with the server, relying on this session for delivery. We want to implement the server-side broadcast to the client, we need to get to the currently active all sessions, we look at the code to see how to get all the sessions

  

// gets all sessions that have disconnected sessions that do not appear in the collection

It's simple, we can send a message to the client after we get to the active session, where we let the server schedule the server time to the client

Timer timer =NewTimer (data) =            {                varmsg =string. Format ("Server Current time: {0:HH:MM:SS}", DateTime.Now); //broadcasts all currently connected sessions                foreach(varSessioninchwsserver.getallsessions ()) {session.                Send (msg); }            }, NULL, +, +);

This allows all clients that remain connected to the server to receive messages from the servers.

In this example, we see that all messages are made by the session object, and the message of the session object send supports both "text" and "binary", while the session object also provides a sendclosehandshakeresponse () Method sends a forced disconnect instruction to the client.

The Websocketsession object contains all the information about the server and the client, as well as the Websocketserver object itself, and we can use it to do a lot of things, and we'll implement a simple chat room below. The principle of the chat room is that what one person is going to say is sent to the server and then broadcast by the server to everyone in the chat room. Well, that's so easy. We came up with the code, it's not explained, it's pretty simple.

  

  Public classChatwebsocket {Private Const stringIP ="127.0.0.1"; Private Const intPort = the; PrivateWebsocketserver ws =NULL;//Websocketserver objects in the Superwebsocket         PublicChatwebsocket () {ws=NewWebsocketserver ();//Instantiate Websocketserver//Adding event listenersWs. newsessionconnected + = ws_newsessionconnected;//a new session handshake and a successful connectionWs. sessionclosed + = ws_sessionclosed;//there is a session being shut down that may be the server shutdown or the client shutting downWs. Newmessagereceived + = ws_newmessagereceived;//a client sends a new message        }        voidWs_newsessionconnected (websocketsession session) {Console.WriteLine ("{0:HH:MM:SS} creates a new session with client: {1}", DateTime.Now, Getsessionname (session)); varmsg =string. Format ("{0:hh:mm:ss} {1} enters chat room", DateTime.Now, Getsessionname (session));        Sendtoall (Session, MSG); }        voidWs_sessionclosed (websocketsession session, SuperSocket.SocketBase.CloseReason value) {Console.writ Eline ("{0:HH:MM:SS} session with client: {1} was closed because: {2}", DateTime.Now, Getsessionname (session), value); varmsg =string. Format ("{0:hh:mm:ss} {1} left chat room", DateTime.Now, Getsessionname (session));        Sendtoall (Session, MSG); }        voidWs_newmessagereceived (websocketsession session,stringvalue) {            varmsg =string. Format ("{0:hh:mm:ss} {1} said: {2}", DateTime.Now, Getsessionname (session), value);        Sendtoall (Session, MSG); }        /// <summary>        ///Start the service/// </summary>        /// <returns></returns>         Public voidStart () {if(!ws. Setup (IP, port)) {Console.WriteLine ("chatwebsocket Setting WebSocket service listening address failed"); return; }            if(!ws. Start ()) {Console.WriteLine ("chatwebsocket Boot WebSocket service failed to listen"); return; } Console.WriteLine ("chatwebsocket Start Service successful"); }        /// <summary>        ///Stop listening Service/// </summary>         Public voidStop () {if(ws! =NULL) {ws.            Stop (); }        }        Private stringGetsessionname (websocketsession session) {//It's not too scientific to use path to get name ...            returnHttputility.urldecode (session. Path.trimstart ('/')); }        Private voidSendtoall (websocketsession session,stringmsg) {            //Broadcast            foreach(varSendsessioninchsession.            Appserver.getallsessions ()) {sendsession.send (msg); }        }    }
View Code

The basic use of Superwebsocket is introduced here ... With the boss from time to glance at the pressure of the screen, may be a bit incoherent article, I hope that we have a lot of understanding, but also hope that we have valuable advice to learn together. Next I'll consider introducing the "sub-Protocol" and the processing of the JSON string type data provided by Superwebsocket

The sample code is downloaded here

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.