日期:2014-05-20  浏览次数:20878 次

请教关于.Net Remoting获取远程对象的问题,请高手指点,分不多了,见谅。。
//请看我下面的代码,问题在后面的释里面:

using   System;
using   System.Collections.Generic;
using   System.Text;

using   System.Runtime.Remoting;
using   System.Runtime.Remoting.Channels;
using   System.Runtime.Remoting.Channels.Tcp;

//定义远程对象
class   FriendListClass   :   MarshalByRefObject
{
public   string[]   names=new   string[0];
}

//服务端
class   ServerPoint
{
static   void   Main(string[]   Args)
{
//创建一个服务器端的实例   :   myFriends
FriendListClass   myFriends=new   FriendListClass();
myFriends.names=new   string[2];
myFriends.names[0]= "Jim ";
myFriends.names[0]= "Lucy ";
//注册通道
TcpChannel   c=new   TcpChannel(1357);
ChannelServices.RegisterChannel(c);
                RemotingConfiguration.RegisterWellKnownServiceType(
                        typeof(FriendListClass),   "myURI ",   WellKnownObjectMode.Singleton);
Console.ReadKey();
}
}

//客户端
class   ClientPoint
{
static   void   Main(string[]   Args)
{
//注册通道
ChannelServices.RegisterChannel(new   TcpChannel());
FriendListClass   myClientFriends=(FriendListClass)Activator.GetObject(
typeof(FriendListClass), "tcp://localhost:1357/myURI ");

//这里是问题所在
Console.WriteLine(myClientFriends.names.Length);
//这里输出的是0,也就是说,客户端得到的,只是一个新的实例,
//而不是服务器端已有的   myFriends   对象实例,
//请问,如果我想得服务器端已经初始化,并且已赋值的对象实例,该如何做呢?
                //简单地说,就是这样,把服务器端对象成员的数据,显示到客户端上,比如
                foreach   (string   name   in   myClientFriends.names)
                {
                        Console.WriteLine( "a   Friend   called   {0} ",name);
                }
Console.ReadKey();
}
}

------解决方案--------------------
static void Main(string[] Args)
{
//创建一个服务器端的实例 : myFriends
FriendListClass myFriends=new FriendListClass();
myFriends.names=new string[2];
myFriends.names[0]= "Jim ";
myFriends.names[0]= "Lucy ";
//注册通道
TcpChannel c=new TcpChannel(1357);

//------------------ 用这一行注册对象
RemotingServices.Marshal(myFriends, "myUri ", typeof(FriendListClass));

Console.ReadKey();
}

-----------------------------------------
http://pointlessly.blogspot.com