自己动手学Remoting(一)

来源:互联网 发布:member.php 编辑:程序博客网 时间:2024/05/16 05:55

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 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);
  }
 
 }
}
 

这个是Server端文件主要在服务端需要创建的对象以及调用的方法.

 

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

namespace ShareDLL
{
 public interface InterMyService
 {
  string SayHello(string AName);
  
  
 }

这个是ShareDLL中间层(更应该叫接口)

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");
   
   Console.WriteLine(Service.SayHello("你好"));
   Console.ReadLine();
  }
 }
}

这是Client 客户端,通过接口直接访问远程对象的映射,

原创粉丝点击