1、服务端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
using GeneralService;
namespace RemotingServer
{
public class Server
{
public static int Main(string[] args)
{
//TCP协议传输消息的信道实现
TcpChannel chan1 = new TcpChannel(8085);
//为远程调用实现使用HTTP协议传输消息的客户端通道
HttpChannel chan2 = new HttpChannel(8086);
//提供帮助进行远程处理信道注册、解析和URL发现的静态方法。无法继承此类
ChannelServices.RegisterChannel(chan1, false);
ChannelServices.RegisterChannel(chan2,false);
//提供多种配置远程结构的静态方法
RemotingConfiguration.RegisterWellKnownServiceType
(
typeof(HelloServer),
"SayHello",
WellKnownObjectMode.Singleton
);
System.Console.WriteLine("Press Enter key to exit");
System.Console.ReadLine();
return 0;
}
}
}2、服务类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace GeneralService
{
public class HelloServer : MarshalByRefObject
{
public HelloServer()
{
Console.WriteLine("HelloServer activated");
}public String HelloMethod(String name)
{
Console.WriteLine(
"Server Hello.HelloMethod : {0}", name);
return "Hi there " + name;
}
}}
3、客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
using GeneralService;namespace RemotingClient
{
public class Client
{
public static void Main(string[] args)
{
//使用TCP通道得到远程对象
TcpChannel chan1 = new TcpChannel();
ChannelServices.RegisterChannel(chan1,false);
//Activator包含特定的方法,用以在本地或从远程创建对象类型、或获取对现有远程对象的引用。无法继承此类
HelloServer obj1 = (HelloServer)Activator.GetObject(
typeof(GeneralService.HelloServer),
"tcp://localhost:8085/SayHello");
if (obj1 == null)
{
System.Console.WriteLine(
"Could not locate TCP server");
}
//使用HTTP通道得到远程对象
HttpChannel chan2 = new HttpChannel();
ChannelServices.RegisterChannel(chan2,false);
HelloServer obj2 = (HelloServer)Activator.GetObject(
typeof(GeneralService.HelloServer),
"http://localhost:8086/SayHello");
if (obj2 == null)
{
System.Console.WriteLine(
"Could not locate HTTP server");
}Console.WriteLine(
"Client1 TCP HelloMethod {0}",
obj1.HelloMethod("Caveman1"));
Console.WriteLine(
"Client2 HTTP HelloMethod {0}",
obj2.HelloMethod("Caveman2"));
Console.ReadLine();
}
}
}