第一次尝试写一个简单的入门实例
废话不多说,全程记录如何开发.net remoting
第一步:新建类库项目RemoteHello
Hello.cs代码如下:
namespace RemoteHello { public class Hello : System.MarshalByRefObject//允许在支持远程处理的应用程序中跨应用程序域边界访问对象。 { public Hello() { } public string SayHello(string name) { return name+"你好,欢迎光临!"; } } }
点击生成,在bin文件夹下将得到一个RemoteHello.dll
这用来创建一个.NET Remote客户端和服务器端用来通讯的“共享命令集”。
第二部:创建简单的服务器
这里我们采用控制台应用程序:新建一个HelloServer的控制台应用程序
代码如下:
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;//引用System.Runtime.Remoting.dll
using RemoteHello;
namespace HelloServer
{
public class HelloServer
{
[STAThread]
public static void Main(string[] args)
{
TcpServerChannel channel = new TcpServerChannel(8088);
bool ensureSecurity = true;//确保安全
ChannelServices.RegisterChannel(channel,ensureSecurity);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Hello), "Hi", WellKnownObjectMode.SingleCall);
System.Console.WriteLine("正在运行.....");
System.Console.ReadLine();
}
}
}
第三步:创建简单的客户机(简单的控制台应用程序)
详见代码:
using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteHello;
namespace HelloClient
{
public class HelloClient
{
public static void Main(string[] args)
{
ChannelServices.RegisterChannel(new TcpClientChannel(),true);
Hello obj = (Hello)Activator.GetObject(typeof(Hello), "tcp://localhost:8088/Hi");
if (obj == null)
{
Console.WriteLine("could not locate server");
return;
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine(obj.SayHello("孙悟空"));
}
}
}
}
注意,HelloServer以及ClientServer都要引用上面生成的RemoteHello.dll
至此,代码编程就完成了。貌似很简单,其实复杂的原理都是这样的。
运行效果服务端:
运行效果客户端:
OK,收工。
浙公网安备 33010602011771号