刚开始不能跟客户端互动,所以必须要考虑如何跟客户端互动!于是就通过对象传递(而不是单纯调用方法)来实现这个目标.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
namespace Server
{
class Server
{
static void Main(string[] args)
{
TcpChannel tcpChannel = new TcpChannel(9012);
//把tcpChannel对象注册到ChannelServices中
ChannelServices.RegisterChannel(tcpChannel, false);
//注册一个Remoting对象ServiceImpl(对象类型,对象名称,创建类型)
RemotingConfiguration.RegisterWellKnownServiceType(typeof(ServiceImpl), "ServiceTest", WellKnownObjectMode.Singleton);
Console.WriteLine("Server is Running");
Console.ReadLine();
Console.ReadLine();
}
}
//建立一个继承MarshalByRefObject和自己定义接口的Class
public class ServiceImpl : MarshalByRefObject, ShareDLL.InterMyService
{
public string SayHello(string AName)
{
return string.Format("Hello {0}", AName);
}
public ShareDLL.ICAOObject CreateCAO(string AName)
{
return new ICAOImpl(AName);
}
}
//(Client Activate Object) CAO 创建一个客户端激活的对象类
public class ICAOImpl : MarshalByRefObject, ShareDLL.ICAOObject
{
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public string SayHelloCAO()
{
return string.Format("Hello {0}, I'm CAO ", _Name);
}
public ICAOImpl(string AName)
{
_Name = AName;
}
}
}
以上是Server
using System;
using System.Collections.Generic;
using System.Text;
namespace ShareDLL
{
public interface InterMyService
{
string SayHello(string AName);
//调用这个方法创建一个对象
ICAOObject CreateCAO(string AName);
}
//定义一个客户端激活对象接口
public interface ICAOObject
{
string Name { get;set;}
string SayHelloCAO();
}
}
以上是中间层,特别注意的是增加了一个对象类别的接口,这样才能真正实现在客户端实例化一个对象.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace Client
{
class Client
{
static void Main(string[] Args)
{
TcpChannel tcpChannel = new TcpChannel(); //因为客户端不需要CallBack端口
ChannelServices.RegisterChannel(tcpChannel, false);
//取得远程的Remoting对象
ShareDLL.InterMyService Service = (ShareDLL.InterMyService)Activator.GetObject(typeof(ShareDLL.InterMyService),
"tcp://10.0.1.52:9012/ServiceTest");
ShareDLL.ICAOObject obj1 = Service.CreateCAO("Brian"); //在客户端映射创建一个对象
ShareDLL.ICAOObject obj2 = Service.CreateCAO("KaiWei");
Console.WriteLine(obj1.SayHelloCAO()); //可以直接使用这个对象
obj1.Name = "Love ";
Console.WriteLine(obj1.SayHelloCAO());
Console.WriteLine(obj2.SayHelloCAO());
Console.ReadLine();
}
}
}
以上就是client端内容!