views:

168

answers:

3

There can be several instances of my service on the same computer, each of them on a different port.

How can I retrieve the port number from which the current request came through to differentiate them?

To clarify, if client is calling the following method:

class OrdersService : MarshalByRefObject
{
    public void EnqueueOrder(Order order)
    {
        //int port = ??
    }
}

I need the port number from which the request was made.

PS: I tried implementing the IServerChannelSink interface but it can only access the URI (like /foo/bar) and IP address of the client.

Thanks

A: 

If you require to call back to the client, then that should be a part of your contract:

public void EnqueueOrder(Order order, IClient client)
{
  // Work with the order.

  // Call back to the client.
}

On the client side, you would implement the IClient interface with a class that derives from MarshalByRefObject, and pass that to the EnqueueOrder method.

casperOne
A: 

This is heinous, and not very generalized, but should work for you:

TcpChannel       channel = (TcpChannel)ChannelServices.RegisteredChannels[0];
ChannelDataStore data    = (ChannelDataStore)channel.ChannelData;
string           uri     = data.ChannelUris[0];
int              port    = int.Parse(uri.Substring(uri.LastIndexOf(':')));

Note that you'll need a reference to System.Runtime.Remoting.dll and you'll need usings for System.Runtime.Remoting.Channels, and System.Runtime.Remoting.Channels.Tcp.

Of course, if you have more than one channel registered, and/or it's not TCP, and/or you have more than one URI for the channel, then you'll have to write better code than the hack-job I did above, but it should give you the idea, anyway.


How are these separate server instances started, anyway? How is the port selected in the first place? How does the client discover the port? The answers to these questions may reveal a more ideal method for distinguishing the instance within the server's code, such as an instance identifier passed on the command line.

P Daddy
A: 

@casperOne

No, I'm not connecting to the client. I need to know the port in which the request is been made.

@PDaddy

I open multiple TcpChannels (one for each Server in the same process) so indexing with RegisteredChannels would be the same problem as finding out the port. Server instances are started like this:

string basePath = "/foo/bar";
int port1 = 5555;
var server1 = new RemotingServer(basePath, port1);
server1.Start();

int port2 = 6666;
var server2 = new RemotingServer(basePath, port2);
server2.Start();

When a request is been received I need to differenciate between server1 and server2 and since the only difference is the port number I need to find that.

Thanks