(2)最简单的Remoting程序
(1) 编写3步走
(类库)对象General
(控制台应用程序)服务器端Server:添加对象的dll引用
(控制台应用程序)客户端Client:添加对象的dll引用
(2) 对象
using System;
using System.Collections.Generic;
using System.Text;
namespace RemotingExample
{
public class Hello : MarshalByRefObject
{
public Hello()
{
Console.WriteLine("Hello对象被建立");
}
public string SayHello(string strClientName)
{
return " Hello ! " + strClientName;
}
}
}
(3) 服务期端代码
using System;
using System.Collections.Generic;
using System.Text;
//添加的using
using RemotingExample;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
//添加System.Runtime.Remoting引用才能添加以下2个using
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
namespace RemotingExample
{
public class Server
{
public static int Main(string[] args)
{
TcpChannel myTcpChannel = new TcpChannel(8085);//申请tcp通道
HttpChannel myHttpChannel = new HttpChannel(8086);//申请http通道
ChannelServices.RegisterChannel(myTcpChannel, false);//注册tcp通道
ChannelServices.RegisterChannel(myHttpChannel, false);//注册http通道
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(Hello),
"SayHello",
WellKnownObjectMode.Singleton
);
System.Console.WriteLine(" Press Enter key to exit ");
System.Console.ReadLine();
return 0;
}
}
}
(4) 客户端代码
using System;
using System.Collections.Generic;
using System.Text;
//添加的using
using RemotingExample;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
//添加System.Runtime.Remoting引用才能添加以下2个using
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
namespace RemotingExample
{
class Client
{
public static int Main(string[] args)
{
//使用TCP通道获得远程对象
TcpChannel myTcpChannel = new TcpChannel();
ChannelServices.RegisterChannel(myTcpChannel, false);
Hello myHelloTCP = (Hello)Activator.GetObject(typeof(Hello), "tcp://localhost:8085/SayHello");
if (myHelloTCP == null)
{
System.Console.WriteLine("Could not locate TCP server");
}
//使用HTTP通道获得远程对象
HttpChannel myHttpChannel = new HttpChannel();
ChannelServices.RegisterChannel(myHttpChannel, false);
Hello myHelloHTTP = (Hello)Activator.GetObject(typeof(Hello), "http://localhost:8086/SayHello");
if (myHelloHTTP == null)
{
System.Console.WriteLine("Could not locate TCP server");
}
//[TCP]调用远程对象的方法
System.Console.WriteLine("TCP: " + myHelloTCP.SayHello("miclu"));
//[HTTP]调用远程对象的方法
System.Console.WriteLine("HTTP: " + myHelloHTTP.SayHello("miclu"));
System.Console.ReadLine();
return 0;
}
}
}
这样代码就写死了,下节学习使用Remoting配置文件