Sunday, November 22, 2009

Remoting server in c#

Create a remoting object (who's methods are RPC) over TCP like this on the server:
MyRemotingObject LocalRemotingObject = new MyRemotingObject();
LocalRemotingObject.MySetupBeforePublishing();
ChannelServices.RegisterChannel( new TCPChannel( MyPort ), false );
ObjRef LocalRef = RemotingServices.Marshal( LocalRemotingObject, "MyRemotingService" );

You can then use LocalRemotingObject like a normal object with straight function calls on the server. Clients use it as normal - with Activator.GetObject() to get a proxy. To destroy the remoting object:
RemotingServices.Unmarshal( LocalRef );
RemotingServices.Disconnect( LocalRemotingObject);
LocalRemotingObject = null;

Some benefits with this approach (instead of using RegisterWellKnownServiceType):

  1. Function call performance on the server is optimal.
  2. You control the time of creation/destruction of the server object explicitly.
  3. You can call functions on the LocalRemotingObject before it has been published as a service, without having to worry about clients trying to use the object at the same time. (Like the call to MySetupBeforePublishing above.)
  4. Using these methods, you can shutdown and restart your remoting service at runtime.

No comments:

Post a Comment