学习技术知识一个好的方法是先动手,再深入,
给出一个最简单的Remoting程序示例(C#)如下:
Step1:创建类库(DLL)工程RemotingObjects,类Person代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemotingObjects
{
public interface IPerson
{
String getName(String name);
}
public class Person : MarshalByRefObject, IPerson
{
public Person()
{
Console.WriteLine("[Person]:Remoting Object 'Person' is activated.");
}
public String getName(String name)
{
return name;
}
}
}
Step2:创建控制台工程RemotingServer(添加项目引用RemotingObjects),类Server代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Text;
using System.Threading.Tasks;
namespace RemotingServer
{
class Server
{
static void Main(string[] args)
{
TcpChannel channel = new TcpChannel(8080);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingObjects.Person), "RemotingPersonService", WellKnownObjectMode.SingleCall);
System.Console.WriteLine("Server:Press Enter key to exit");
System.Console.ReadLine();
}
}
}
Step3:创建控制台工程RemotingClient(添加项目引用RemotingObjects及必要类库),类Client代码如下:
(PS:正式应用开发,不需要也不应该直接引用RemotingObjects类库,而应该引用相关Remoting类的接口库。)
using RemotingObjects;
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 RemotingClient
{
class Client
{
static void Main(string[] args)
{
TcpChannel channel = new TcpChannel();
ChannelServices.RegisterChannel(channel, false);
IPerson obj = (IPerson)Activator.GetObject(typeof(RemotingObjects.IPerson), "tcp://localhost:8080/RemotingPersonService");
if (obj == null)
{
Console.WriteLine("Couldn't crate Remoting Object 'Person'.");
}
Console.WriteLine("Please enter your name:");
String name = Console.ReadLine();
try
{
Console.WriteLine(obj.getName(name));
}
catch (System.Net.Sockets.SocketException e) {
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
}
}
Step4:运行编译出的EXE:RemotingServer.exe和RemotingClient.exe,查看运行结果。
於太阳宫
2014/01/21