首页 > 其他 > 详细

Remoting 学习一

时间:2014-02-20 08:19:05      阅读:302      评论:0      收藏:0      [点我收藏+]

Remoting

 

使用TCP/IP 协议,服务端可以是服务,web服务器,类。

 

例子1.  远程调用服务端的类,就像调用客户端机器上的类一样。

 

服务端代码 (先定义被客户端调用的类,然后注册到某个端口中去,客户端访问刚才注册地址  ip:端口号/类名)

 

1)类

类实现加法运算

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

namespace ConsoleApplication1
{
    public class RemotingSample:MarshalByRefObject
    {
        public RemotingSample()
        {
            Console.WriteLine("New References Added");
        }

        public int sum(int a, int b)
        {
            return a + b;
        }

    }
}

 

注:MarshalByRefObject   允许在支持远程处理的应用程序中跨应用程序域边界访问对象

 

2)服务端控制端应用程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime;

using System.Runtime.Remoting.Channels.Tcp;           //引用中必须加入 System.Runtime.Remoting 才能使用
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpServerChannel chanel = new TcpServerChannel(6666);
            ChannelServices.RegisterChannel(chanel);

            RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingSample), "RemotingSample", WellKnownObjectMode.SingleCall);
            Console.WriteLine("请按下任意键");

            Console.ReadKey();
        }
    }
}

 

 

3)客户端。控制端应用程序

 

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

using System.Runtime;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Tcp;
using ConsoleApplication1;
namespace Rclient
{
    class Program
    {
        static void Main(string[] args)
        {
            ChannelServices.RegisterChannel(new TcpClientChannel(),true);

            RemotingSample remoteObj = (RemotingSample)(Activator.GetObject(typeof(RemotingSample), "tcp://localhost:6666/RemoteSample"));

            Console.WriteLine("1+2="+remoteObj.sum(1,2).ToString());
            Console.ReadKey();
        }
    }
}

 

 

 

 

开始调用,首先启动服务端程序实现注册端口和服务

bubuko.com,布布扣

 

客户端开始调用远程的类

bubuko.com,布布扣

 

 

 

总结:

1.使用下面的命名空间

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

 

2.

注册TCP端口供客户端调用

TcpServerChannel chanel = new TcpServerChannel(6668);
ChannelServices.RegisterChannel(chanel);

接着注册Remoting服务

RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingSample), "RemotingSample", WellKnownObjectMode.SingleCall);

 

3. 客户端使用

调用TCP://ip:服务端注册的端口号/服务端注册的类

Remoting 学习一

原文:http://www.cnblogs.com/StudyLife/p/3556731.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!