cad.net 跨程序通訊Remoting
阿新 • • 發佈:2021-07-10
cad跨程序通訊Remoting
正在研究cad的跨程序通訊,
難點在於cad是服務端的話,讓客戶端直接呼叫暴露的介面,而不會暴露實現,
因此寫了一個Remoting的案例,如下程式碼就可以進行了.
至於WCF工程,由於它的App.config處理有些地方不是很理解,之後再仔細研究.
工程結構
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); } }
(完)