using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemoteHello
{
public class Hello:System.MarshalByRefObject
{
string name;
public Hello()
{
Console.WriteLine("Constructor called");
}
public void SetName(string name)
{
this.name = name;
}
public string Greeting()
{
Console.WriteLine("Greeting called");
return "Hi~~" + this.name;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteHello;
namespace HelloServer
{
class Program
{
static void Main(string[] args)
{
//在服务器端创建TcpServerChannel信道
var channel = new TcpServerChannel(8086);
//注册该信道,使之可用于远程对象。
ChannelServices.RegisterChannel(channel, true);
//用于为服务器激活的对象注册远程对象类型,(把知名的远程对象类型注册为 RemotingServices)
//第一个参数是 typeof(Hello),它指定远程对象的类型。第二个参数 Hi 是远程对象的 URI, 客户端访问远程对象时要使用这个 URI。 最后一个参数是远程对象的模式。
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Hello), "Hi~~", WellKnownObjectMode.SingleCall);
Console.WriteLine("Press return to exit");
Console.ReadLine();
}
}
}
using RemoteHello;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Text;
using System.Threading.Tasks;
namespace HelloClient
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press return after the server is started");
Console.ReadLine();
//在客户端创建TcpServerChannel信道
ChannelServices.RegisterChannel(new TcpClientChannel(), true);
//GetObject()它调用Remoting Services.Connect()方法以 返回远程对象的代理对象。第一个参数指定远程对象的类型。第二个参数是远程对象的URL。
Hello obj = (Hello)Activator.GetObject(typeof(Hello), "tcp://localhost:8086/Hi~~");
// Hello obj = (Hello)RemotingServices.Connect(typeof(Hello),"tcp://localhost:8086/Hi");
if (obj == null)
{
Console.WriteLine("could not locate server");
return;
}
obj.SetName("TomHanks");
for (int i = 0; i < 5; i++)
{
Console.WriteLine(obj.Greeting());
}
Console.ReadLine();
}
}
}
/*
Press return to exit
Constructor called
Constructor called
Greeting called
Constructor called
Greeting called
Constructor called
Greeting called
Constructor called
Greeting called
Constructor called
Greeting called
请按任意键继续. . .
Press return after the server is started
Hi~~
Hi~~
Hi~~
Hi~~
Hi~~
请按任意键继续. . .
*/