Remoting asynchronous callbacks to broadcast messages to online users

Source: Internet
Author: User

Purpose of this article: to broadcast messages to the remoting online client.

The main techniques used: Async, Callback, broadcast.

Implementation process:

Defining a remote instance

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Runtime.Remoting.Messaging;namespaceremoteobject{//defining delegates, displaying callback messages     Public Delegate voidShowcallbackmsg (stringSTR1,stringstr2); //remote instances generated by the client for the server to invoke callbacks     Public classOnlinecallback:marshalbyrefobject {//How the client implements the delegate         Publicshowcallbackmsg showmsg; //callback for service-side invocation         Public voidCallBack (stringSTR1,stringstr2) {            if(ShowMsg! =NULL) {Showmsg.invoke (str1, str2); }        }    }    //remote instances running on the server     Public classRemoteobject:marshalbyrefobject {//static variables record each client generates a remote instance for the callback         Public StaticList<onlinecallback> Listonline =NewList<onlinecallback>();  PublicRemoteObject () {}//to add a client-side build for the callback remote instance         Public voidAddonlinecallback (Onlinecallback xcallback) {listonline.add (xcallback); }        //with OneWay, asynchronous execution, the client issues the execution command, that is, no longer waiting for return, referred to the server callback processing[System.Runtime.Remoting.Messaging.OneWay] Public voidDoSomething (stringSTR1,stringSTR2,intisleep) {            //to see the effect, wait a long timeSystem.Threading.Thread.Sleep (Isleep); //perform callbacks on all registered online remote instances, broadcast messages            foreach(Onlinecallback Xcallbackinchlistonline)            {Xcallback.callback (str1, str2); }        }    }}

Service side:

usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Runtime.Remoting;usingSystem.Runtime.Remoting.Channels;usingSYSTEM.RUNTIME.REMOTING.CHANNELS.TCP;namespaceremoteserver{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent ();        } TcpChannel Chan1; Private voidButton1_Click (Objectsender, EventArgs e) {            //Start the service side            Try{IDictionary tcpproperties=NewHashtable (); tcpproperties["name"] ="RemoteTest"; //Specify the service porttcpproperties["Port"] =int.                                            Parse (TextBox1.Text); Binaryclientformattersinkprovider Tcpclientsinkprovider=NewBinaryclientformattersinkprovider (); BinaryServerFormatterSinkProvider Tcpserversinkprovider=NewBinaryServerFormatterSinkProvider (); Tcpserversinkprovider.typefilterlevel=System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; Chan1=NewTcpChannel (tcpproperties, Tcpclientsinkprovider, Tcpserversinkprovider);                ChannelServices.RegisterChannel (CHAN1); RemotingConfiguration.RegisterWellKnownServiceType (typeof(Remoteobject.remoteobject),"RemoteTest", Wellknownobjectmode.singleton); MessageBox.Show ("Start success!"); Button1. Enabled=false ; Button2. Enabled=true ; }            Catch(Exception ex) {MessageBox.Show (ex).            Message); }        }        //Stop service Side        Private voidButton2_Click (Objectsender, EventArgs e) {            Try            {                if(Chan1! =NULL) {Channelservices.unregisterchannel (chan1); }            }            Catch(Exception ex) {MessageBox.Show (ex).            Message); } button1. Enabled=true; Button2. Enabled=false; }    }}

Client

usingSystem;usingSystem.Collections.Generic;usingSystem.Collections;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Runtime.Remoting;usingSystem.Runtime.Remoting.Channels;usingSystem.Runtime.Remoting.Services;usingSYSTEM.RUNTIME.REMOTING.CHANNELS.TCP;namespaceremoteclient{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } TcpChannel chan1=NULL; Remoteobject.remoteobject obj1=NULL; Private voidBtnconnect_click (Objectsender, EventArgs e) {            //connecting to the service side            Try{IDictionary tcpproperties=NewHashtable (); Binaryclientformattersinkprovider Tcpclientsinkprovider=NewBinaryclientformattersinkprovider (); BinaryServerFormatterSinkProvider Tcpserversinkprovider=NewBinaryServerFormatterSinkProvider (); Tcpserversinkprovider.typefilterlevel=System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; //to prevent clients from having more than one network card IP, specify the use of IP that can communicate with the server                if(BtnBindIp.Text.Trim (). Length >0) tcpproperties["BindTo"] =Btnbindip.text; tcpproperties["Timeout"] =5; //This is critical, 0 means listening on all ports, is the necessary condition for receiving server callbackstcpproperties["Port"] =0; Chan1=NewTcpChannel (tcpproperties, Tcpclientsinkprovider, Tcpserversinkprovider); //registering a communication pipelineChannelServices.RegisterChannel (CHAN1); Obj1=(Remoteobject.remoteobject) Activator.GetObject (typeof(remoteobject.remoteobject),"tcp://"+ Txtsrvip.text +":"+ Txtsrvport.text +"/remotetest"); //to generate a client remote instance for a service-side callbackRemoteobject.onlinecallback Xcallback =NewRemoteobject.onlinecallback (); //to specify a method for receiving processing service-side callbacksXcallback.showmsg =Newremoteobject.showcallbackmsg (xcallback_showmsg); //invoking the server-side remote method Addonlinecallback, logging the client remote instanceobj1.                Addonlinecallback (Xcallback); Btnconnect.enabled=false; Btninvoke.enabled=true; }            Catch(Exception ex) {MessageBox.Show (ex).                Message); Btnconnect.enabled=true; Btninvoke.enabled=false; }        }        Private voidBtnbreak_click (Objectsender, EventArgs e) {            Try            {                //Disconnect ConnectionChannelservices.unregisterchannel (CHAN1); Obj1=NULL; }            Catch(Exception ex) {MessageBox.Show (ex).            Message); } btnconnect.enabled=true; Btnbreak.enabled=false; }        Private voidBtninvoke_click (Objectsender, EventArgs e) {            Try            {                              //call the remote method of the service-side RemoteObject (its method is oneway asynchronous mode)Obj1. DoSomething ("AAA","BBB", the); }            Catch(Exception ex) {MessageBox.Show (ex).            Message); }        }        //Methods for handling service-side callback messages        voidXcallback_showmsg (stringSTR1,stringstr2) {MessageBox.Show (str1+str2); }    }}

Remoting asynchronous callbacks to broadcast messages to online users

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.