远程开发分布式C#编程实例

场景模拟:某公司希望所有员工能够知道新项目的详细资料。项目的详细资料须作为管道访问的远程对象上的一个方法来调用。客户端作一个演示实现管道注册,并接受用户名及密码,数据发送给组件,并应该能够返回。
远程对象(RemoteTest)代码部分:

using System;

namespace RemoteTest
{
  
public   class TestLoader:MarshalByRefObject
   {
       
public TestLoader()
        {
           
string stringWrite =   " stor load. " ;
           Console.WriteLine(stringWrite);
        }
      
public   string sayHello( string userName, string pwd)
       {
           Console.WriteLine(
" User Name: { 0 } Password: { 1 } " ,userName, pwd);
           Console.WriteLine(
" Welcome to Presto Systems " );

          
string stc =   " Hello from remote " ;
          
return stc;
        }
    }
}

我的理解:
TestLoader类继承了System.MarshalByRefObject类,便让客户端能访问该远程对象了。


服务端(Server)代码部分:

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

namespace Server
{
  
public   class Program
   {
      
public   static   void Main( string [] args)
       {
           TcpServerChannel channel
=   new TcpServerChannel( 9932 );
           ChannelServ ices.RegisterChannel(channel);
           RemotingConfiguration.RegisterWellKnownServiceType(
typeof (TestLoader), " TestLoader " ,WellKnownObjectMode.SingleCall);
           Console.WriteLine(
" Hello From Server " );
           Console.ReadLine();
        }
    }
}

注:引用添加组件:System.Runtime.Remoting(下同)。

客户端(Client)代码部分:

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

namespace Client
{
  
public   class ClassClient
   {
      
public   static   void Main( string [] args)
       {
          
string userName;
          
string pwd;
          
string stringTcp =   " tcp://localhost:9932/TestLoader " ;
           TestLoader loader
= (TestLoader)Activator.GetObject( typeof (RemoteTest.TestLoader),stringTcp);
          
           Console.Write(
" Enter User Name: " );
           userName
= Console.ReadLine();
           Console.WriteLine(
" User Name: "   + userName);
           Console.Write(
" Enter Password: " );
           pwd
= Console.ReadLine();
           Console.WriteLine(
" Password: "   + pwd);
          
string res = loader.sayHello(userName,pwd);
           Console.WriteLine(res);
          
        }
    }
}

这里对new <script src="/editor/tiny_mce/themes/advanced/langs/zh.js" type="text/javascript"></script> 管道声明的那两行已略写。

程序调试:启动Server后,再启动Client。输入值后关闭Client,值便在Server中显示。

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页