Reputation: 4228
How can I truly dispose/release the TCP Channel(port) in code without application exit in my .NET remoting application?
The full code can be found on GitHub.
private static void Main(string[] args)
{
Console.WriteLine("Server side ....");
while (true)
{
Console.WriteLine();
Console.WriteLine("Press S for stopping service, others for start ...");
var key = Console.ReadKey();
if (key.Key == ConsoleKey.S)
{
var channel = ChannelServices.GetChannel("x");
ChannelServices.UnregisterChannel(channel);
Console.WriteLine("TCP Channel stopped!!!");
}
else
{
var provider = new BinaryServerFormatterSinkProvider
{
TypeFilterLevel = TypeFilterLevel.Full
};
var props = new Hashtable
{
{"port", 25253},
{"name", "x"}
};
var channel = new TcpServerChannel(props, provider);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(People), "p",
WellKnownObjectMode.Singleton);
Console.WriteLine("TCP Channel started!!!");
}
}
}
private static void Main(string[] args)
{
Console.WriteLine("Client side ....");
var i = 0;
while (true)
{
try
{
var p = (People) Activator.GetObject(typeof(People), "tcp://localhost:25253/p");
p.SetAge(i);
Console.WriteLine($"{i} succeed => {p.Age}");
Thread.Sleep(2000);
}
catch (Exception ex)
{
Console.WriteLine($"{i} failed ==> {ex.Message}");
}
i++;
}
}
Besides that, I use following PS command to check port usage:
Get-Process -Id (Get-NetTCPConnection -LocalPort 25253).OwningProcess
While the channel was unregistered in Server, the port are still used by Server process.
Note: I am aware of another issue that even channel was unregistered, the client can still connect and operate successfully. There are some cache there, but anyway this is not an issue. What I want is the Port can be released without application terminated.
Upvotes: 2
Views: 239