二、利用事件实现客户端向服务器通信
接着上一篇,按照我的思路,远程对象中定义的事件在客户端触发,而在服务器端订阅,应该可以成功。现在放弃之前的示例代码,自己重新写一个版本,代码如下:
远程对象:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Remoting
{
public class RemotingObject:MarshalByRefObject
{
public delegate void MyDelegate(string msg);
public static event MyDelegate myEvent;
//触发事件
public void TriggerEvent(string msg)
{
if (myEvent != null)
myEvent(msg);
}
//无限生命周期
public override object InitializeLifetimeService()
{
return null;
}
}
}
服务器:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using Remoting;
namespace Server
{
public partial class ServerForm : Form
{
public ServerForm()
{
InitializeComponent();
StartServer();
}
//开启服务器
public void StartServer()
{
TcpChannel tcpchannel = new TcpChannel(8080);
ChannelServices.RegisterChannel(tcpchannel,false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingObject),"url",WellKnownObjectMode.Singleton);
RemotingObject.myEvent += new RemotingObject.MyDelegate(RemotingObject_myEvent);
}
void RemotingObject_myEvent(string msg)
{
//跨线程调用
textBox2.Invoke(new Action<st