现假设有一个留言板程序:
以下代码中,MsgBoard为以Singleton模式存活于服务器端的共享留言板实例,AddMessage是客户端添加留言的接口, MsgBoard定义如下:
public class MsgBoard:MarshalByRefObject
{
public delegate void EventDelegate(string info);
public event EventDelegate OnInfoAdded;
public void AddMessage(string info)
{
Console.WriteLine(info);
if(OnInfoAdded!=null)
OnInfoAdded(info);
}
}
在有客户端添加留言时,激发一个事件,我们的客户端去订阅该事件来得到留言板更新的通知。服务器端代码如下:
Using directives#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Serialization.Formatters;/**//////
#endregion
namespace ConsoleServer
{
class Program
{
static void Main(string[] args)
{
RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyLibrary.MsgBoard), "MyUri", WellKnownObjectMode.
Singleton);
HttpChannel myChannel = new HttpChannel(1080);
ChannelServices.RegisterChannel(myChannel);
/**///////
IServerChannelSink sc = myChannel.ChannelSinkChain;
while (sc != null)
{
if (sc is BinaryServerFormatterSink)
{
((BinaryServerFormatterSink)sc).TypeFilterLevel = TypeFilterLevel.Full;
//break;
}
if (sc is SoapServerFormatterSink)
{
((SoapServerFormatterSink)sc).TypeFilterLevel = TypeFilterLevel.Full;
//break;
}
sc = sc.NextChannelSink;
}
Console.WriteLine("Server Started");
Console.ReadLine();
}
}
}
我们可以不要详细去关心服务器端程序的代码,我们只需要知道:
1,服务器注册了远程服务的类型
2,TypeFilterLevel = TypeFilterLevel.Full
由于从.NET Framework 1.1起,缺省情况下DelegateSerializationHolder不允许被反序列化,(即FormatterSink.TypeFilterLevel = TypeFilterLevel.low)。为了实现远程事件处理,我们必须解除该约束,使ServerFormatterSink.TypeFilterLevel = TypeFilterLevel.Full
我们更加需要关心的是我们的客户端代码: