Click here to Skip to main content
6,595,444 members and growing! (18,421 online)
Email Password   helpLost your password?
General Programming » Internet / Network » Remoting     Intermediate

Remote methods and events in C#

By san77in

An article on Remoting in C#
C#, Windows, .NET, Visual Studio, Dev
Posted:6 Sep 2003
Views:90,359
Bookmarked:35 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
21 votes for this article.
Popularity: 4.72 Rating: 3.57 out of 5
3 votes, 14.3%
1
2 votes, 9.5%
2
4 votes, 19.0%
3
5 votes, 23.8%
4
7 votes, 33.3%
5

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.

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

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

About the Author

san77in


Member
I am Sanjeev Krishnan.
Occupation: Web Developer
Location: India India

Other popular Internet / Network articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 30 (Total in Forum: 30) (Refresh)FirstPrevNext
Generalnotify the client if the server ip address changes Pinmembersaisunil_d11:56 13 Jan '09  
GeneralUnhandled Exception: System.IO.FileNotFoundException PinmemberMember 55529943:13 26 Sep '08  
GeneralConfigure Time to live Pinmembermanaf5:59 11 Jul '05  
GeneralRe: Configure Time to live Pinmemberigal.p3:27 5 Dec '05  
GeneralHow about a GUI example Pinsusssecovel12349:43 4 Apr '05  
GeneralRe: How about a GUI example Pinmemberfmccown3:47 30 Apr '05  
GeneralUsing retrieved data in the client PinmemberRyanHilton12:14 27 Jan '05  
GeneralRe: Using retrieved data in the client PinmemberJacob Anderson8:23 8 Feb '06  
GeneralWhy the two methods Pinmember42Kent4213:06 9 Nov '04  
GeneralRe: Why the two methods Pinmembermikeperetz16:42 11 Jan '05  
GeneralHere are fixes to get this working!! Pinsussbducks20:49 8 Apr '04  
GeneralRe: Here are fixes to get this working!! Pinsussbducks21:37 8 Apr '04  
GeneralRe: Here are fixes to get this working!! PinmemberMember 15230945:52 17 Aug '08  
Generalwindows forms type server? Pinmemberbitvadasz90422:42 2 Mar '04  
GeneralRe: windows forms type server? Pinsussbducks20:33 8 Apr '04  
GeneralThe Configuration PinsussAnonymous8:52 20 Feb '04  
GeneralRe: The Configuration Pinmembermanaf1:18 10 Jul '05  
GeneralThank You Pinmemberjparsons10:59 21 Oct '03  
Generalmultiple clients Pinmemberkrdoki@email.ro5:58 8 Oct '03  
GeneralRe: multiple clients PinsussChris Gibbons13:53 14 May '04  
GeneralRe: multiple clients Pinmembermanaf1:06 10 Jul '05  
GeneralRe: multiple clients Pinmembermanaf1:36 10 Jul '05  
GeneralRe: multiple clients PinmemberIPC20007:08 15 Mar '06  
GeneralSecurityException Pinmemberbalesteros13:27 20 Sep '03  
GeneralRe: SecurityException PinmemberMarkyMarc9:40 23 Dec '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 6 Sep 2003
Editor: Nishant Sivakumar
Copyright 2003 by san77in
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project