REMOTING是.NET自带的一种RPC调用方式。主要解决多个进程间互相的调用。
原来:建立一个公用的对象,该对象在服务端声明并共享出去,各个进程可以取到这个公共的对象,并修改该对象。如希望实现一个进程调用另一个进程,那么使用代理来实现该目的。TCP连接效率较快,但是基本只能用于本机。HTTP效率较慢,但是可以用于局域网。注意,服务端和客户端必须使用相同的协议。
项目结构
新建一个接口:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public interface IReceiveData {
void Talk(string word);
}
}
实现接口
namespace ClassLibrary1
{
[Serializable]
/// <summary>
///
/// </summary>
public class ReceiveData : MarshalByRefObject, IReceiveData
{
/// <summary>
/// 说话
/// </summary>
/// <param name="word"></param>
public void Talk(string word)
{
System.Console.WriteLine(word);
}
}
}
服务端同时注册IPC 和TCP通道
internal class Program
{
static void Main(string[] args)
{
//注册IPC通道
IpcServerChannel channel = new IpcServerChannel("testIpc"); //端口随便取
ChannelServices.RegisterChannel(channel, true);
//注册远程对象
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(ReceiveData),
"ReceiveData",
WellKnownObjectMode.SingleCall);
//注册Tcp通道
TcpServerChannel tcpChannel = new TcpServerChannel(809); //端口随便取
ChannelServices.RegisterChannel(tcpChannel, true);
//注册远程对象
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(ReceiveData),
"SenData",
WellKnownObjectMode.SingleCall);
Console.WriteLine("服务 启动");
Console.ReadLine();
}
}
客户端只需引用接口库便可以调用两个服务接口了:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Channels.Tcp;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ClassLibrary1;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
try
{
IpcClientChannel ipcClient = new IpcClientChannel();
ChannelServices.RegisterChannel(ipcClient, true);
IReceiveData logFun = (IReceiveData)RemotingServices.Connect(typeof(IReceiveData), "ipc://testIpc/ReceiveData");
logFun.Talk("abcdddd");
//注册通道
TcpClientChannel channel = new TcpClientChannel();
ChannelServices.RegisterChannel(channel, true);
//获取远程对象
var _talk = (IReceiveData)Activator.GetObject(typeof(IReceiveData), "TCP://localhost:809/SenData");
_talk.Talk("asdfadsfasdfadsfa");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
总结:ipc通道即连即用非常的丝滑。tcp通道首次发送会卡顿,应该是tcp握手连接导致的的。 实现效果如下。
服务端
客户端