using System;
using System.Collections;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("press any key plus enter to create server: ");
if (Console.ReadLine().Length > 0)
{
var serverProv = new BinaryServerFormatterSinkProvider();
serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
IDictionary props = new Hashtable();
props["port"] = 17017;
props["name"] = "tcp server";
var channel = new TcpChannel(props, null, serverProv);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Server), "server",
WellKnownObjectMode.Singleton);
Console.WriteLine("Server created");
}
else
{
ChannelServices.RegisterChannel(new TcpChannel(), false);
Server server = (Server)Activator.GetObject(typeof(Server), "tcp://localhost:17017/server");
Client client = new Client();
client.Connect(server);
}
Console.ReadLine();
}
}
class Server : MarshalByRefObject
{
//private List<Client> cilents = new List<Client>();
public event EventHandler ClientedAdded;
public void AddClient(Client client)
{
if (ClientedAdded != null)
{
foreach (EventHandler handler in ClientedAdded.GetInvocationList())
{
handler.BeginInvoke(this, EventArgs.Empty, null, null);
}
}
}
}
class Client : MarshalByRefObject
{
public void Connect(Server server)
{
server.ClientedAdded += server_ClientedAdded;
server.AddClient(this);
}
void server_ClientedAdded(object sender, EventArgs e)
{
Console.WriteLine("server_ClientedAdded");
}
}
}
First, run the exe and create a server. Then run the exe and create a client by pressing Enter directly.
The exception will be thrown at handler.BeginInvoke(this, EventArgs.Empty, null, null);
.
This remoting proxy has no channel sink which means either the server has no registered server channels that are listening, or this application has no suitable client channel to talk to the server.
So how to fix it?
I found a similar question on http://www.codeguru.com/forum/showthread.php?t=420124. The author provided a solution but it is too brief for me to understand.
I solved it!
Just try using
handler(this, EventArgs.Empty)
rather than
handler.BeginInvoke(this, EventArgs.Empty, null, null);
I got an exception saying can not call a private method.
Then the problem is clear and I make server_ClientedAdded public.
Now the code works!