cad.net 跨进程通讯Remoting

cad跨进程通讯Remoting

正在研究cad的跨进程通讯,
难点在于cad是服务端的话,需要将服务端的函数给暴露出来,让客户端直接调用,而暴露的时候最好只是暴露接口,不暴露函数实现.
如下就可以进行了.

工程结构

1.服务端工程 --> cad的类库,透过cad调用 --> 引用端口工程
2.客户端工程 --> 控制台工程 --> 引用端口工程
3.端口工程 --> 类库

1.服务端工程

#if !HC2020
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Acap = Autodesk.AutoCAD.ApplicationServices.Application;
#else
using GrxCAD.ApplicationServices;
using GrxCAD.DatabaseServices;
using GrxCAD.EditorInput;
using Acap = GrxCAD.ApplicationServices.Application;
#endif
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System;
using JoinBox.IAdapter;
namespace JoinBox.Service
{
    public class Remoting
    {  
        /// <summary>
        /// 注册服务管道remoting,实现占用端口
        /// </summary>
        [JoinBoxInitialize]
        public void RegisterServerChannel()
        {
            var channel = new TcpServerChannel(AdapterHelper.Port);
            ChannelServices.RegisterChannel(channel, false);
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(BaseService),         //服务端对接口的实现
                nameof(IJoinBoxAdapter),     //客户端调用的公共接口,例如此处末尾:tcp://localhost:15341/IJoinBoxAdapter
                WellKnownObjectMode.Singleton);
        }
    }

    // 实现公共接口,在cad命令栏打印
    public class BaseService : MarshalByRefObject, IJoinBoxAdapter
    {
        public void PostAcedString(string str)
        {
            AutoGo.SyncManager.SyncContext.Post(() => {
                Document doc = Acap.DocumentManager.MdiActiveDocument;
                Database db = doc.Database;
                Editor ed = doc.Editor;
                ed.WriteMessage(str);
            });
        }
    }
}

2.客户端工程 JoinBox.Client

using System;
using System.Threading;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using JoinBox.IAdapter;

namespace JoinBox.Client
{
    public class Program
    {
        public static void Main(string[] args)
        {
            ChannelServices.RegisterChannel(new TcpClientChannel(), false);
            var remoteobj = (IJoinBoxAdapter)Activator.GetObject(typeof(IJoinBoxAdapter), AdapterHelper.TcpPortStr);
            while (true)
            {
                var str = DateTime.Now.ToString() + "\n";
                Console.WriteLine(str);
                remoteobj.PostAcedString(str);
                Thread.Sleep(1000);
            }
        }
    }
}

3.接口工程 JoinBox.IAdapter

此工程同时暴露给服务端和客户端利用

namespace JoinBox.IAdapter
{
    //暴露出去的接口
    public interface IJoinBoxAdapter
    {
        public void PostAcedString(string str);
    }

    //公共占用的东西
    public class AdapterHelper
    {
        public static int Port          = 15341;
        public static string TcpPortStr = $"tcp://localhost:{Port}/" + nameof(IJoinBoxAdapter);
    }
}

(完)

上一篇:c#-Windows窗体应用程序的性能测试


下一篇:C#-如何在服务结构中为服务远程调用设置超时