remoting项目运用

xiaoxiao2025-05-25  32

上次写了remoting 的简单运用,在项目中我们服务端与客户端肯定不会去直接调用一个类,一般都是通过接口。下面我将自己项目里的一部分代码截取出来,进行讲解首先编写接口

编写接口

namespace YTKJ.Security.Interface { public interface IMachineControlService { void OpenDoor(string door, string direction); }

为了简单理解,接口中只写了一个方法,下来我在服务端将实现这个接口。

实现接口

namespace PSIMS.Machine.Control { public delegate void OpenDoorEventHandler(string door, string direction); [Serializable] class MachineControlService : MarshalByRefObject,IMachineControlService { public static event OpenDoorEventHandler OpenDoorEvent; /// <summary> /// 重载初始化生命周期,改为永久 /// </summary> /// <returns></returns> public override object InitializeLifetimeService() { return null; } public void OpenDoor(string door, string direction) { if (OpenDoorEvent != null) { OpenDoorEvent(door ,direction); } } } }

在这里首先实现类需要实现MarshalByRefObject接口,为OpenDoor方法设置了事件和委托。下来我们看看服务端应该怎么注册remoting服务。

注册Remoting服务

TcpServerChannel channels; channels = new TcpServerChannel(20001); ChannelServices.RegisterChannel(channels, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(MachineControlService), "YTKJ.Security.Interface.IMachineControlService", WellKnownObjectMode.Singleton); MachineControlService.OpenDoorEvent += new OpenDoorEventHandler(MachineControlService_OpenDoor); /// <summary> /// 打开门操作 /// </summary> /// <param name="door"></param> /// <param name="direction"></param> private void MachineControlService_OpenDoor(string door, string direction) { //这里写你的操作 }

这样服务端做的事情就完成了,下来我们看看客户端怎么调用

客户端调用

IMachineControlService a; a= (YTKJ.Security.Interface.IMachineControlService)Activator.GetObject(typeof(YTKJ.Security.Interface.IMachineControlService), "tcp://192.168.11.10:20001/YTKJ.Security.Interface.IMachineControlService"); a.OpenDoor("","");

客户端的调用很简单,声明接口,使用方法获得远程调用接口,调用接口中的方法。这里有个需要注意的问题,在客户端调用的类型YTKJ.Security.Interface.IMachineControlService一定要与服务端的命名空间和接口名一致,否则客户端会报无法加载类型的异常 这样启动项目远程调用就完成了。

转载请注明原文地址: https://www.6miu.com/read-5030703.html

最新回复(0)