Remoting 学习一调用远程的类就像调用本地的类一样
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); //本机调用true,false都可以
RemotingSample remoteObj = (RemotingSample)(Activator.GetObject(typeof(RemotingSample), "tcp://localhost:6666/RemotingSample"));
Console.WriteLine("1+2="+remoteObj.sum(1,2).ToString());
Console.ReadKey();
}
}
}
开始调用,首先启动服务端程序实现注册端口和服务
客户端开始调用远程的类
查看本地端口,6668服务端口,22034是客户端主机随便分配的端口号。
总结:
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); ///服务端注册tcp端口
ChannelServices.RegisterChannel(chanel);
接着注册Remoting服务
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingSample), "RemotingSample", WellKnownObjectMode.SingleCall);
3. 客户端使用
调用TCP://ip:服务端注册的端口号/服务端注册的类
Console.WriteLine("1+2="+remoteObj.sum(1,2).ToString());
最新文章
- 告别编译运行 ---- Android Studio 2.0 Preview发布Instant Run功能
- ci 基础知识
- nginx linux 下开机自动启动
- CRM SQL 创建活动 ActivityPointer
- python 抽象类、抽象方法的实现
- Oracle查询慢, 特别是更新慢问题
- apache服务器参数设置
- 自己通过反射写的一个属性copy类
- python3.6----datetime.timedelta
- 从零学习Fluter(三):Flutter的路由跳转以及state的生命周期
- eclipse中如何自动生成构造函数
- aiohttp的笔记之TCPConnector
- IOS 将状态栏改为白色
- springboot项目接入配置中心,实现@ConfigurationProperties的bean属性刷新方案
- Spring之使用表达式配置切入点
- git: error while loading shared libraries: libiconv.so.2
- 读CSV文件
- java 打包jar 并后台运行
- platform_driver_probe 函数解析
- [arc065E]Manhattan Compass[曼哈顿距离和切比雪夫距离转换]