您的位置:首页 > 其它

.NET Remoting服务器端订阅客户端事件

2012-01-07 22:06 393 查看
模拟情景:在天龙八部中,有信使通知住持,说,带头大哥说契丹人要来抢经书了。客户端订阅服务器端事件,于是向服务器端发送消息。

1.服务器端代码,设计服务器端要提供的服务

namespace RemotingLib

{

/// <summary>

/// 拨通电话的委托,

/// </summary>

/// <param name="msg">电话中要传输的消息</param>

public delegate void PhoneUpEventHandler(string msg);

public interface ICall

{

void PhoneUp(string msg);

}

public class RemotePhone : MarshalByRefObject, ICall

{

public static event PhoneUpEventHandler PhoneUpEvent;

#region ICall 成员

public void PhoneUp(string msg)

{

PhoneUpEvent(msg);

}

#endregion

/// <summary>

/// 设置对象的生命周期无限大。意味着这个远程对象始终处于激活状态,以便能够激活事件

/// </summary>

/// <returns></returns>

public override object InitializeLifetimeService()

{

return null;

}

}

}

2.将提供服务的对象公布出来

class Program

{

static int count = 0;

static void Main(string[] args)

{

//1.注册通信通道

TcpChannel tChannel = new TcpChannel(8888);

ChannelServices.RegisterChannel(tChannel);

//2.在通道中注册对象,不同的激活方式对应不同的注册方式

//服务端激活

RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotePhone), "yoyo", WellKnownObjectMode.Singleton);

RemotePhone.PhoneUpEvent += new PhoneUpEventHandler(RemotePhone_PhoneUpEvent);

Console.WriteLine(DateTime.Now);

Console.ReadKey();

}

static void RemotePhone_PhoneUpEvent(string msg)

{

count+=1;

Console.WriteLine("第" + count + "个人说:" + msg);

}

}

3.客户端调用远程对象代码

class Program

{

static void Main(string[] args)

{

//注意:客户端不能使用端口号,否则报错:套接字遇到一个已死的网络

TcpChannel tChannel = new TcpChannel();

ChannelServices.RegisterChannel(tChannel);

ICall call = (ICall)Activator.GetObject(typeof(ICall), "tcp://localhost:8888/yoyo");

call.PhoneUp("住持,带头大哥说契丹人要来抢经书了");

Console.ReadKey();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: