Callback processing of the message of the socket development framework

Source: Internet
Author: User

Callback processing of the message of the socket development framework

In the general socket application, most of the time the data sent and received are processed separately, that is, we send a message, do not know when the request message received the reply message, and receive the corresponding reply message, if the content of the interface, also need to deal with special, Because they are not together with the interface thread. It would be much easier if we were able to send a callback code to a reply message when we were sending the message. This article mainly introduces how to implement the callback function in the socket application, the corresponding function can be called when the reply message is received.

1. Design of callback function

In the previous essay, the entity class design of the JSON-based socket message was introduced, including the message callback ID and whether to remove the callback two properties after the call, which is used to process the service for the callback, as shown below.

That is, add the following two properties to the generic Message object Basemessage class.

But when we need to send a message, we add the ID of the callback to the local collection, and when we get the answer, we put it in the collection and execute it.

        <summary>///        Send data Objects in a common format///</summary>//        <param name= "data" > Generic Message Object </param >        //<returns></returns> public bool SendData (basemessage data, Delegate callBack = null)        {            Addcallback (callBack, data);//Add callback set            var tosenddata = packmessage (data);            var result = SendData (tosenddata);            return result;        }
        <summary>////        Record callback function information///</summary>//        <param name= "CallBack" ></param>        //<param name= "MSG" ></param>        private void Addcallback (Delegate callBack, basemessage msg)        {            if (callBack! = null)            {                Guid callbackid = Guid.NewGuid ();                Responsecallbackobject responsecallback = new Responsecallbackobject ()                {                    ID = callbackid,                    CallBack = CallBack                };                Msg. Callbackid = Callbackid;                Callbacklist.add (Responsecallback);            }        }

On the server side, the response needs to be built based on the requested message, so we need to copy the callback ID of the request to the body of the reply, as shown below, when we answer the request.

        <summary>        ///package data Send (copy request part of data)///</summary>//        <returns></returns> Public        basemessage Packdata (basemessage request)        {            Basemessage info = new Basemessage ()            {                Msgtype = this. Msgtype,                Content = this. SerializeObject (),                callbackid = Request. Callbackid            };            if (!string. IsNullOrEmpty (Request. Touserid))            {                info. Touserid = Request. Fromuserid;                Info. Fromuserid = Request. Touserid;            }            return info;        }

2, the local callback function processing and interface processing

When the caller receives the reply message from the server, it calls out from the local collection and executes the processing according to the ID of the callback, which realizes the operation of our callback.

                var MD5 = md5util.getmd5_32 (message. Content);                if (MD5 = = message. MD5)                {                    invokemessagecallback (message, message). Deletecallbackafterinvoke);//Trigger Callback                    onmessagereceived (message);//overload for subclass                }
        <summary>////Execute callback function///</summary>//        <param name= "MSG" > Message Base Object </param>        //<param name= "Deletecallback" > whether to remove callbacks </param>        private void Invokemessagecallback ( Basemessage msg, bool Deletecallback)        {            var callbackobject = callbacklist.singleordefault (x = = X.id = Msg. Callbackid);            if (callbackobject! = null)            {                if (deletecallback)                {                    callbacklist.remove (callbackobject);                }                CallBackObject.CallBack.DynamicInvoke (msg);            }        }

This way, when we call, we pass in the action of a callback so that we can execute it dynamically after receiving the message. For example, when landing, if we need to display the main form after successful login, then we can execute the following processing code.

            var request = new Authrequest (userno, password); var message = Request.            Packdata (); Singleton<commonmanager>. Instance.send (Message, (msg) = = {var Instance = Singleton<commonmanager>.                Instance; try {var response = jsontools.deserializeobject<authresponse> (msg.                    Content); if (response. Validateresult = = 0) {instance. Showloadformtext ("Login successful, load base data ....")                        ");                        Place initialization Code Portal.gc.User = new User (Userno); Instance.                        Setclientid (Userno); Instance.                        Showmainform (); Instance.                    Closeloadform (); } else {instance.                        Closeloadform (); Instance. ShowMessage ("Login failed:" + response.                        Message); InstanCe.                    Showlogin (); }} catch (Exception ex) {instance. ShowMessage ("Initialize exception:" + ex.)                    Message); Instance.                Exit (); }            });

Or let's take a look at another example, this example is to request an online user list when the user logs in, if the user is online, then the list is displayed on the interface, and the operation code is as follows, and the callback function is used to handle it.

        <summary>///Send a request to get a list of online users and make a local interface update after receiving the response data//</summary> private void Ref            Reshuser () {commonrequest request = new Commonrequest (datatypekey.userlistrequest); var data = Request.            Packdata (); Singleton<commonmanager>. Instance.send (data, msg) = {Userlistresponse response = Jsontools.deserializeobject<use Rlistresponse> (Msg.                Content); if (response! = NULL) {this.                        Invokeui (() = {this.listView1.Items.Clear (); foreach (Clistitem item in response. UserList) {if (item. Value! = Portal.gc.User.UserNo) {THIS.LISTVIEW1.ITEMS.ADD (item.                            Text, 0);                }                        }                    });            }}); }

For example, after the client logs on to several users, the user can get a list of online users, the interface shown below.

The above is the implementation of the callback function that we handle in the socket application, so that the processing can use the callback code to encapsulate the details of the processing, for understanding the relevant answer operation is also very intuitive.

Callback processing of the message of the socket development framework

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.