(原创)一步一步学Remoting之六:事件(1)
一步一步学Remoting之六:事件(1)
周末又过去了要上班了,一大早起来继续写。
概念就不说了,具体参见msdn相关章节:
http://msdn.microsoft.com/library/CHS/cpguide/html/cpconEvents.asp
我们先来改造一下上次的程序,为上次的主线程方法添加事件,能不断的引发事件来汇报处理的进度:
public class MyEventArgs
{
private int _rate;
public int Rate
{
get
{
return _rate;
}
}
public MyEventArgs(int rate)
{
this._rate=rate;
}
}
public class MyObject
{
public delegate void MyEventHandler(object sender,MyEventArgs e);
public event MyEventHandler MyEvent;
public void ALongTimeMethod(int time)
{
Console.WriteLine("主线程方法开始");
for(int i=0;i<100;i++)
{
System.Threading.Thread.Sleep(time);
OnMyEvent(new MyEventArgs(i));
}
Console.WriteLine("主线程方法结束");
}
protected void OnMyEvent(MyEventArgs e)
{
if (MyEvent!=null)
{
MyEvent(this,e);
}
}
}
{
private int _rate;
public int Rate
{
get
{
return _rate;
}
}
public MyEventArgs(int rate)
{
this._rate=rate;
}
}
public class MyObject
{
public delegate void MyEventHandler(object sender,MyEventArgs e);
public event MyEventHandler MyEvent;
public void ALongTimeMethod(int time)
{
Console.WriteLine("主线程方法开始");
for(int i=0;i<100;i++)
{
System.Threading.Thread.Sleep(time);
OnMyEvent(new MyEventArgs(i));
}
Console.WriteLine("主线程方法结束");
}
protected void OnMyEvent(MyEventArgs e)
{
if (MyEvent!=null)
{
MyEvent(this,e);
}
}
}
再来为事件添加处理程序:
class MyClient
{
[STAThread]
static void Main(string[] args)
{
DateTime dt=DateTime.Now;
MyObject obj=new MyObject();
obj.MyEvent+=new MyObject.MyEventHandler(obj_MyEvent);
obj.ALongTimeMethod(50);
Console.WriteLine("用了"+((TimeSpan)(DateTime.Now-dt)).TotalSeconds+"秒");
Console.ReadLine();
}
public static void obj_MyEvent(object sender,MyEventArgs e)
{
Console.WriteLine("主线程方法完成了"+e.Rate+"%");
}
}
{
[STAThread]
static void Main(string[] args)
{
DateTime dt=DateTime.Now;
MyObject obj=new MyObject();
obj.MyEvent+=new MyObject.MyEventHandler(obj_MyEvent);
obj.ALongTimeMethod(50);
Console.WriteLine("用了"+((TimeSpan)(DateTime.Now-dt)).TotalSeconds+"秒");
Console.ReadLine();
}
public static void obj_MyEvent(object sender,MyEventArgs e)
{
Console.WriteLine("主线程方法完成了"+e.Rate+"%");
}
}
运行程序可以看到:
这个是本地的,远程对象的事件也这么简单吗?其实没有想象的简单,因为对象是在远程的,服务端的事件客户端怎么捕捉?应该说远程对象的事件可以分成客户端触发-》服务器应答,服务端触发-》客户端应答和客户端触发-》客户端应答,第一种就很简单了,后面2种都需要有一个中间件。下面我们来要为程对象同样来添加一个进度机制,首先来建立我们的远程对象:
[Serializable]
public class MyEventArgs:EventArgs
{
private int _rate;
private string _ip;
public int Rate
{
get
{
return _rate;
}
}
public string IP
{
get
{
return _ip;
}
}
public MyEventArgs(int rate,string ip)
{
this._rate=rate;
this._ip=ip;
}
}
public class MyObject:MarshalByRefObject
{
public delegate void MyEventHandler(object sender,MyEventArgs e);
public event MyEventHandler MyEvent;
public int ALongTimeMethod(int a,int b,int time,string ip)
{
Console.WriteLine("异步方法开始");
for(int i=0;i<10;i++)
{
System.Threading.Thread.Sleep(time);
OnMyEvent(new MyEventArgs(i,ip));
}
Console.WriteLine("异步方法结束");
return a+b;
}
protected void OnMyEvent(MyEventArgs e)
{
if (MyEvent!=null)
{
MyEvent(this,e);
}
}
}
public class MyEventArgs:EventArgs
{
private int _rate;
private string _ip;
public int Rate
{
get
{
return _rate;
}
}
public string IP
{
get
{
return _ip;
}
}
public MyEventArgs(int rate,string ip)
{
this._rate=rate;
this._ip=ip;
}
}
public class MyObject:MarshalByRefObject
{
public delegate void MyEventHandler(object sender,MyEventArgs e);
public event MyEventHandler MyEvent;
public int ALongTimeMethod(int a,int b,int time,string ip)
{
Console.WriteLine("异步方法开始");
for(int i=0;i<10;i++)
{
System.Threading.Thread.Sleep(time);
OnMyEvent(new MyEventArgs(i,ip));
}
Console.WriteLine("异步方法结束");
return a+b;
}
protected void OnMyEvent(MyEventArgs e)
{
if (MyEvent!=null)
{
MyEvent(this,e);
}
}
}
为了调试方便,服务器端和客户端这次都用程序实现,下面是服务器端:
using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
namespace RemoteServer
{
class MyServer
{
[STAThread]
static void Main(string[] args)
{
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject.MyObject),"RemoteObject.MyObject",WellKnownObjectMode.Singleton);
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary props = new Hashtable();
props["port"]=9999;
TcpChannel channel = new TcpChannel(props,clientProvider,serverProvider);
ChannelServices.RegisterChannel(channel);
Console.ReadLine();
}
}
}
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
namespace RemoteServer
{
class MyServer
{
[STAThread]
static void Main(string[] args)
{
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject.MyObject),"RemoteObject.MyObject",WellKnownObjectMode.Singleton);
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary props = new Hashtable();
props["port"]=9999;
TcpChannel channel = new TcpChannel(props,clientProvider,serverProvider);
ChannelServices.RegisterChannel(channel);
Console.ReadLine();
}
}
}
客户端为了简单一点,我去除了前面做测试的本地事件:
using System;
using System.Net;
using System.Collections;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
class MyClient
{
private delegate int MyDelegate(int a,int b,int time,string ip);
private static MyDelegate md;
[STAThread]
static void Main(string[] args)
{
DateTime dt=DateTime.Now;
RemotingConfiguration.RegisterWellKnownClientType(typeof(RemoteObject.MyObject), "tcp://localhost:9999/RemoteObject.MyObject");
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary props=new Hashtable();
props["port"]=0;
TcpChannel channel = new TcpChannel(props,clientProvider,serverProvider);
ChannelServices.RegisterChannel(channel);
RemoteObject.MyObject app=new RemoteObject.MyObject();
app.MyEvent+=new RemoteObject.MyObject.MyEventHandler(MyEvent);
md=new MyDelegate(app.ALongTimeMethod);
AsyncCallback ac=new AsyncCallback(MyClient.CallBack);
IPHostEntry ipHE=Dns.GetHostByName(Dns.GetHostName());
IAsyncResult Iar=md.BeginInvoke(1,2,300,ipHE.AddressList[0].ToString(),ac,null);
Method();
Console.WriteLine("用了"+((TimeSpan)(DateTime.Now-dt)).TotalSeconds+"秒");
ChannelServices.UnregisterChannel(channel);
Console.ReadLine();
}
public static void CallBack(IAsyncResult Iar)
{
if(Iar.IsCompleted)
{
Console.WriteLine("结果是"+md.EndInvoke(Iar));
}
}
public static void MyEvent(object sender,RemoteObject.MyEventArgs e)
{
Console.WriteLine("来自"+e.IP+"的异步方法完成了"+e.Rate*10+"%");
}
public static void Method()
{
Console.WriteLine("主线程方法开始");
System.Threading.Thread.Sleep(5000);
Console.WriteLine("主线程方法结束");
}
}
using System.Net;
using System.Collections;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
class MyClient
{
private delegate int MyDelegate(int a,int b,int time,string ip);
private static MyDelegate md;
[STAThread]
static void Main(string[] args)
{
DateTime dt=DateTime.Now;
RemotingConfiguration.RegisterWellKnownClientType(typeof(RemoteObject.MyObject), "tcp://localhost:9999/RemoteObject.MyObject");
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary props=new Hashtable();
props["port"]=0;
TcpChannel channel = new TcpChannel(props,clientProvider,serverProvider);
ChannelServices.RegisterChannel(channel);
RemoteObject.MyObject app=new RemoteObject.MyObject();
app.MyEvent+=new RemoteObject.MyObject.MyEventHandler(MyEvent);
md=new MyDelegate(app.ALongTimeMethod);
AsyncCallback ac=new AsyncCallback(MyClient.CallBack);
IPHostEntry ipHE=Dns.GetHostByName(Dns.GetHostName());
IAsyncResult Iar=md.BeginInvoke(1,2,300,ipHE.AddressList[0].ToString(),ac,null);
Method();
Console.WriteLine("用了"+((TimeSpan)(DateTime.Now-dt)).TotalSeconds+"秒");
ChannelServices.UnregisterChannel(channel);
Console.ReadLine();
}
public static void CallBack(IAsyncResult Iar)
{
if(Iar.IsCompleted)
{
Console.WriteLine("结果是"+md.EndInvoke(Iar));
}
}
public static void MyEvent(object sender,RemoteObject.MyEventArgs e)
{
Console.WriteLine("来自"+e.IP+"的异步方法完成了"+e.Rate*10+"%");
}
public static void Method()
{
Console.WriteLine("主线程方法开始");
System.Threading.Thread.Sleep(5000);
Console.WriteLine("主线程方法结束");
}
}
代码看上去不错,可是debug启动后报错:
这就是我前面提到的问题,远程不可能有本地的程序集,也无法触发本地事件。解决办法就是加一个事件中间件,继承MarshalByRefObject:
public class EventClass:MarshalByRefObject
{
public void MyEvent(object sender,MyEventArgs e)
{
Console.WriteLine("来自"+e.IP+"的异步方法完成了"+e.Rate*10+"%");
}
}
{
public void MyEvent(object sender,MyEventArgs e)
{
Console.WriteLine("来自"+e.IP+"的异步方法完成了"+e.Rate*10+"%");
}
}
然后来修改一下客户端:
把app.MyEvent+=new RemoteObject.MyObject.MyEventHandler(MyEvent);修改为
RemoteObject.EventClass ec=new RemoteObject.EventClass();
app.MyEvent+=new RemoteObject.MyObject.MyEventHandler(ec.MyEvent);
app.MyEvent+=new RemoteObject.MyObject.MyEventHandler(ec.MyEvent);
运行一下程序:
前后两个窗口本别是服务端和客户端的,貌似达到了我们的要求,其实不然,程序有2个漏洞:
1、客户端关闭以后打开新的程序就出错,因为以前的委托链丢失,服务端程序企图触发事件出错。
2、同时打开几个客户端,客户端收到的是所有的进度信息,而不仅仅是自己的,广播性质的消息。
不早了要上班了,在下一节中来改进这2点。
欢迎大家阅读我的极客时间专栏《Java业务开发常见错误100例》【全面避坑+最佳实践=健壮代码】