Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#
Article

Remote methods and events in C#

Rate me:
Please Sign up or sign in to vote.
3.91/5 (21 votes)
6 Sep 20033 min read 166.4K   2.3K   41   35
An article on Remoting in C#

Introduction

This article gives and introduction to remote methods and events using c#.There are many articles already available on Remoting. Most of them deal with the remote methods .This article explains the implementation of a remote event also. This might be of use for beginners.

Reference

Microsoft knowledge Base Article -312114 Explains the changes required for the implementation of remote events. Here I am trying to provide a simpler explanation for the implementation of an event (call back) using the same article as my reference :-)

The component

First we have to create a component which has a method and an event available in it. A new c# project is created as a class library .The component code is added there. The component hosts a method an an event handler as shown below. A global Delegate should also be declared representing the type of the eventhandler. The event handler will hold the callback function pointer. The clients will be subscribing and unsubscribing to this.

C#
 public delegate void myeventhandler(string str);

//component defenition is as below

  public  abstract class AbstractServer : MarshalByRefObject
  {
    public abstract string myfunc(string what);
    public abstract event  myeventhandler myevent;
  }

Also a class that will have the implementation in the client has to be defined as below

C#
public abstract class AbstractBroadcastedMessageEventSink :
  MarshalByRefObject
{
  public void myCallback(string str)
  {
    internalcallback(str);
  }
  protected abstract void internalcallback (string str) ;
}

Server

The server should reference to this component. Here in the source i have done the implementation of the component in the server side. The EventHandler that enables the Subscribing of the client method has to be implemented. Also an internal method FireNewBroadcastedMessageEvent is being included .This method will call the actual call back which the client would have subscribed.

Apart from that the server should also do the functionalities like , open a Tcp Channel, Register that Tcp channel and then register the componet as a well known Service type.T he server used here is a console application. The code that does these functions is as shown below.

C#
using System;
using mycomponent;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
  class Class1
  {
    
    static void Main(string[] args)
    {
      TcpChannel m_TcpChan = new TcpChannel(9999); //open a channel

      ChannelServices.RegisterChannel(m_TcpChan); 

      Type theType = new  ServerClass().GetType();  
          
      RemotingConfiguration.RegisterWellKnownServiceType(
        theType,
        "FirstRemote",                    
        WellKnownObjectMode.Singleton);
  
      System.Console.WriteLine("Press ENTER to quit");
      System.Console.ReadLine();
    }
  }

  //component implementation
    public class ServerClass : AbstractServer
    {
      public override string myfunc(string what)
      {
      Console.WriteLine("in myfunc");
      FireNewBroadcastedMessageEvent("Event: " + what + " was said");
      return "done";
      }

      public event  myeventhandler myHandler;

      public override event myeventhandler myevent
      {
        add
        {
        Console.WriteLine("in event myevent + add");
              
        myHandler = value;
        }

        remove
        {
        Console.WriteLine("in event myevent + remove");
        }
      }

      protected void FireNewBroadcastedMessageEvent(string text)
      {
        Console.WriteLine("Broadcasting...");
        myHandler("hai");
      }

      
    }

Client

The client should first define a class( as EventSink) that implements the "AbstractBroadcastedMessageEventSink " class that was defined in the component.

In normal remoting if we do not need the callbacks, the client has to register a tcpchannel and then initiate the object using the port number and ip address of the remote pc. But as there are call backs ,this client should also open a TCp channel with a different port number. It should then register that TCP channel and also register the EventSink as a wellknown service type .This is because we use the internal method of the EventSink as our callback method .If we do not perform the above operations our callback will not be called. We set the "myevent" handler of the object to the "sink.callback" function. So when we execute the "FireNewBroadcastedMessageEvent" the method "myHandler("hai")" will be called and this internally calls our call back.

C#
using System;
using mycomponent;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
  
  class EventSink : AbstractBroadcastedMessageEventSink
  {
  
    protected override  void internalcallback (string str) 
    {
      Console.WriteLine("Your message in callback ");
    }


  }

  class Class1
  {
    static void Main(string[] args)
    {
      TcpChannel m_TcpChan = new TcpChannel(1011);
      ChannelServices.RegisterChannel(m_TcpChan);


      AbstractServer m_RemoteObject = (AbstractServer)
        Activator.GetObject(typeof(AbstractServer),
        "tcp://SANJEEV:9999/FirstRemote"); 

  //here SANJEEV is my PC name .Here the pcname of the machine 
  //where the server is running has to be given
  //FirstRemore is the name that was given in the 
  //registerwellknownservicetype from the server       

      RemotingConfiguration.RegisterWellKnownServiceType(
        typeof(EventSink),
        "ServerEvents",
        WellKnownObjectMode.Singleton); 

      EventSink sink = new EventSink();
        
      
      Console.WriteLine("Subscribing");
      
          
      m_RemoteObject.myevent += new myeventhandler(sink.myCallback);

      m_RemoteObject.myfunc("Hello");
    }
  }

Testing

Start the Server. Then Start the client. If the call back method gets called. Then Success!!!

Conclusion

I'm posting this article as i found it very difficult to find a simple article on remote events. Hope this will help somebody who is searching for code on remote events . This is the first article that I am posting on this site. Thank you for the time. :-)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
I am Sanjeev Krishnan.

Comments and Discussions

 
Generalnotify the client if the server ip address changes Pin
saisunil_d13-Jan-09 10:56
saisunil_d13-Jan-09 10:56 
GeneralRe: notify the client if the server ip address changes Pin
Moxxis28-Sep-11 21:18
Moxxis28-Sep-11 21:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.