Click here to Skip to main content
Click here to Skip to main content

Remote methods and events in C#

, 6 Sep 2003
Rate this:
Please Sign up or sign in to vote.
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 Smile | :)

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.

 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

  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.

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.

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. Smile | :)

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

Share

About the Author

san77in
Web Developer
India India
I am Sanjeev Krishnan.

Comments and Discussions

 
QuestionWhat? PinmemberMoxxis28-Sep-11 19:05 
AnswerRe: What? PinmemberMoxxis28-Sep-11 22:46 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141220.1 | Last Updated 7 Sep 2003
Article Copyright 2003 by san77in
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid