日期:2014-05-18  浏览次数:20912 次

Remoting在客户端服务器怎么实现?
一道面试题原题!

------解决方案--------------------
第一步:建议server端程序:

1 项目—新建—控制台程序--

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Security.Permissions;

public class Server

{

[SecurityPermission(SecurityAction.Demand)]

public static void Main(string[] args)

{

TcpChannel serverChannel = new TcpChannel(8081);// 8081为为端口号

ChannelServices.RegisterChannel(serverChannel, true);//注册通道

//注册远程对象

RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteTest), "proname", WellKnownObjectMode.Singleton);



Console.WriteLine("Press any KEY to exit the server and stop the channel.");

Console.ReadLine();

serverChannel.StopListening(null); //停止监听

ChannelServices.UnregisterChannel(serverChannel); //注销通道

}

}

第二步:建议client端程序:

项目—新建—控制台程序---

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

using System.Security.Permissions;

public class Client

{

[SecurityPermission(SecurityAction.Demand)]

public static void Main(string[] args)

{



TcpChannel clientChannel = new TcpChannel(); //创建通道



ChannelServices.RegisterChannel(clientChannel,true);//注册通道

//获取远程对象

//(1) WellKnown激活模式调用RemotingConfiguration的静态方法RegisterActivatedClientType()。

/*WellKnownClientTypeEntry remoteType = new WellKnownClientTypeEntry(typeof(RemoteTest), "tcp://192.168.168.165:9090/RemoteObject.rem");

RemotingConfiguration.RegisterWellKnownClientType(RemoteTest);



RemoteTest obj2 = new RemoteTest(); */

//客户端激活模式()调用Activator进程的GetObject()方法

RemoteTest obj2 = (RemoteTest)Activator.GetObject(typeof(RemoteTest), "tcp://192.168.168.165:8081/ proname ");

 

person m = new person("TempUser", "men", "19");

m = obj2.getInfo(m);

Console.WriteLine(m.name);



Console.Read();

}

}

注意看上面代码,两段程序代码里面反复出现RemoteTest,person等字眼,一看就知道这两个是大家自己定义的类,马上我们建立它,“tcp://192.168.168.165:8081/proname”,其中,tcp代表的tcp协议,如果是http当然就应该上http协议了,后面是IP地址和端口号,即服务器端的地址和端口号,后面的proname叫做远程对象服务名,我们暂且不记它,只要保持一致就可以了,其实在程序中对应ApplicationName属性的内容。

回到主题上来,刚才的RemoteTest,person等类都没有,直接编译肯定出错,怎么办,马上解决。

 

第二步:建议远程服务对象:

项目—新建—控制台程序

 注意,这次建立的不需要运行,直接编译成dll文件即可,然后在服务器端和客户端分别添加引用即可,代码如下:

using System;

using System.Runtime.Remoting;

// Remote object.

public class RemoteTest : MarshalByRefObject

{

private int clientCount = 0;

public int ReCount(int i)

{

clientCount = (clientCount++)+i;

return (clientCount);

}

public string HelloWorld(string name)

{

Console.WriteLine("GOOD MORNING!");

return "Hi," + name;

}

public person getInfo(person m)

{

Console.WriteLine("THERE HAVE ONE PERSON INFOMATION HAS RESIVED!");



Console.WriteLine(m.name+"-"+m.age+"-"+