直接上代码:
服务端:
private static string ServerChannelId = $"ScanSnapHome-{Environment.UserName}"; var serverChannel = IpcServerChannelUtil.GetIpcServerChannelInstance(ServerChannelId); ChannelServices.RegisterChannel(serverChannel, true); sharingData = new SharingData(); sharingData.OnNotify += new SharingData.CallEventHandler(OnNotify); // OnNotify 回调函数,就不上传了 RemotingServices.Marshal(sharingData, "SharingData", typeof(SharingData));
class SharingData : MarshalByRefObject { public class HomeDataEventArgs : EventArgs { public string Param { get; private set; } public string SerialNo { get; private set; } public ModeConstant Mode { get; private set; } public string ContentId { get; private set; } public HomeDataEventArgs(string param, string serialNo, ModeConstant mode, string contentId) { this.Param = param; this.SerialNo = serialNo; this.Mode = mode; this.ContentId = contentId; } } public delegate void CallEventHandler(HomeDataEventArgs e); public event CallEventHandler OnNotify; public void DataNotify(string param, string serialNo, ModeConstant mode, string contentId) { OnNotify(new HomeDataEventArgs(param, serialNo, mode, contentId)); } public override object InitializeLifetimeService() { return null; } }
客户端:
clientChannel = new IpcClientChannel(); ChannelServices.RegisterChannel(clientChannel, true); sharingData = (SharingData)Activator.GetObject(typeof(SharingData), $"ipc://{ServerChannelId}/SharingData"); // 服务器中的ServerChannelId变量
这里就完成了,客户端就可以拿到服务器的SharingData对象。