如何使用 .Net Remoting 实现定向广播
相对于 WebService而言,使用.Net Remoting技术的客户端能够订阅服务器端事件。
利用该技术作一个简单而又典型的应用,信息广播程序是一个不错的选择。
以下代码是一个简单的广播程序。
服务端:
代码:
class Program
{
static void Main(string[] args)
{
BinaryServerFormatterSinkProvider sfsp = new BinaryServerFormatterSinkProvider();
sfsp.TypeFilterLevel = TypeFilterLevel.Full;
Hashtable props = new Hashtable();
props["port"] = 8086;
TcpChannel channel = new TcpChannel(props, null, sfsp);
ChannelServices.RegisterChannel(channel, false);
SayHello sayHello = new SayHello();
RemotingServices.Marshal(sayHello, "SayHello");
Console.ReadKey();
sayHello.Say("Mike", "Hello, Mike");
Console.ReadKey();
sayHello.Say("John", "Hello, John");
Console.ReadKey();
}
}
客户端:
代码:
class Program
{
static void Main(string[] args)
{
BinaryServerFormatterSinkProvider sfsp = new BinaryServerFormatterSinkProvider();
sfsp.TypeFilterLevel = TypeFilterLevel.Full;
Hashtable props = new Hashtable();
props["port"] = 0;
TcpChannel channel = new TcpChannel(props, null, sfsp);
ChannelServices.RegisterChannel(channel, false);
SayHello sh = (SayHello)Activator.GetObject(typeof(SayHello), "tcp://localhost:8086/SayHello");
SayEventReappear re = new SayEventReappear();
re.ClientId = "John";
sh.OnSay += new SayHandler(re.Say);
re.OnSay += new SayHandler(re_OnSay);
Console.ReadKey();
}
static void re_OnSay(string text)
{
Console.WriteLine(text);
}
}
远程对象、委托及事件重现器(需同时部署在服务端及客户端):
代码:
public class SayHello : MarshalByRefObject
{
public event SayHandler OnSay;
public void Say(string clientId, string text)
{
if (this.OnSay != null) this.OnSay(text);
}
}
public delegate void SayHandler(string text);
public class SayEventReappear : MarshalByRefObject
{
public event SayHandler OnSay;
public void Say(string text)
{
if (this.OnSay != null) this.OnSay(text);
}
}
信息广播程序就这样完成了。
您可能感兴趣的文章:
如何使用 .Net Remoting 实现定向广播
.Net远程方法调用研究
.NET Remoting 实现分布式数据库查询
.NET Remoting编程简介(转)
Java数据报编程之广播
MSMQ,Enterprise Service, DotNet Remoting,Web Servi
构建基本的.NET Remoting应用程序
jquery实现的超出屏幕时把固定层变为定位层的代码
html5的video(视频)和audio(音频)标签中的属性用法
HTML5 video标签的播放控制