问题:命名空间“System.Runtime.Remoting.Channels”中不存在类型或命名空间名“Tcp”(是否缺少程序集引用?)
解决:项目->添加引用->程序集->选中System.Runtime.Remoting
remmoting:实现进程间通讯,主要是获取远程对象,实际的通讯是通过TCP
实现的流程:
先定义一个继承了MarshalByRefObject 的类,该类是在支持远程处理的应用程序中,允许跨应用程序域边界访问对象
1.定义信道
服务器: TcpServerChannel channels = new TcpServerChannel("TalkChannel", 9000);
TcpServerChannel (string name, int port)
name:信道名称
port:信道监听端口
客户端: TcpClientChannel channel = new TcpClientChannel();
2.注册信道
ChannelServices.RegisterChannel(channel, true);
3.服务器:注册远程对象模型
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Talker), "Talker", WellKnownObjectMode.SingleCall);
typeof(Talker):对象Type
"Talker":对象URI
WellKnownObjectMode.SingleCall:正在被注册的已知对象类型的激活方式 (SingleCall每个传入的消息由新的对象实例提供服务,Singleton每个传入的消息由同一个对象实例提供服务。)
客户端:获取远程对象(Talker)Activator.GetObject(typeof(Talker),"TCP://localhost:9000/Talker");MarshalByRefObject的子类对象
typeof(Talker):希望连接到的已知对象的类型
"TCP://localhost:9000/Talker":已知的URL
具体实现的代码:
MarshalByRefObject的子类
class Talker : MarshalByRefObject
{
public void SendMsg(string text)
{
System.Console.WriteLine(text);
}
}
服务器端代码:
class Program
{
static void Main(string[] args)
{
//注册通道
TcpServerChannel channels = new TcpServerChannel("TalkChannel", 9000);
ChannelServices.RegisterChannel(channels, true);
//注册远程对象
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Talker), "Talker", WellKnownObjectMode.SingleCall);
Console.ReadLine();
}
}
客户端代码:客户端是一个winform程序,包含一个button,一个textBox
public partial class Form1 : Form
{
private Talker talker;
public Form1()
{
InitializeComponent();
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
//操作远程对象
talker.SendMsg(txtBoxMsg.Text);
MessageBox.Show("发送成功:" + txtBoxMsg.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//注册通道
TcpClientChannel channel = new TcpClientChannel();
ChannelServices.RegisterChannel(channel, true);
//获取远程对象
talker = (Talker)Activator.GetObject(typeof(Talker),"TCP://localhost:9000/Talker");
}
}
本文介绍了C# Remoting的概念,用于解决命名空间`System.Runtime.Remoting.Channels`中`Tcp`类型缺失的问题。通过创建`TcpServerChannel`和`TcpClientChannel`实现跨进程通讯,详细讲解了定义信道、注册信道、注册远程对象模型以及获取远程对象的步骤,并提供了具体的代码示例。
2763

被折叠的 条评论
为什么被折叠?



