您的位置:首页 > 其它

一个最简单的.NET Remoting构建的分布式应用程序示例

2006-07-13 14:51 691 查看
服务器端代码
文件名:Server.cs

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
namespace RemotingSamples
{

public class Server
{
public static int Main(string [] args)
{

TcpChannel chan1 = new TcpChannel(8085);
HttpChannel chan2 = new HttpChannel(8086);

ChannelServices.RegisterChannel(chan1);
ChannelServices.RegisterChannel(chan2);

RemotingConfiguration.RegisterWellKnownServiceType
(
typeof(OrderNumber),
"SayHello",
WellKnownObjectMode.Singleton
);

System.Console.WriteLine("Press Enter key to exit");
System.Console.ReadLine();
return 0;
}

}
}

远程对象代码
文件名:OrderNumber.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace RemotingSamples
{
public class OrderNumber : MarshalByRefObject
{
private int djIncNumber;
public OrderNumber()
{
System.Console.WriteLine("服务器端已经被激活……");
}
public int IncOrderNumber()
{
djIncNumber = djIncNumber + 1;
Console.WriteLine("服务被客户端调用{0}次", djIncNumber);
return djIncNumber;
}
}
}

客户端代码
文件名:Client.cs

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
using System.IO;

namespace RemotingSamples
{
public class Client
{
public static void Main(string[] args)
{
//使用TCP通道得到远程对象
TcpChannel chan1 = new TcpChannel();
ChannelServices.RegisterChannel(chan1);
OrderNumber obj1 = (OrderNumber)Activator.GetObject(
typeof(RemotingSamples.OrderNumber),
"tcp://localhost:8085/SayHello");
if (obj1 == null)
{
System.Console.WriteLine(
"Could not locate TCP server");
System.Console.ReadLine();
}
//使用HTTP通道得到远程对象
HttpChannel chan2 = new HttpChannel();
ChannelServices.RegisterChannel(chan2);
OrderNumber obj2 = (OrderNumber)Activator.GetObject(
typeof(RemotingSamples.OrderNumber),
"http://localhost:8086/SayHello");
if (obj2 == null)
{
System.Console.WriteLine(
"Could not locate HTTP server");
System.Console.ReadLine();
}

Console.WriteLine(
"Client1 TCP HelloMethod {0}",
obj1.IncOrderNumber());
Console.WriteLine(
"Client2 HTTP HelloMethod {0}",
obj2.IncOrderNumber());
Console.ReadLine();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐