學習技術知識一個好的方法是先動手,再深入,
給出一個最簡單的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