关于Remoting的个人使用心得

时间:2023-03-09 16:33:24
关于Remoting的个人使用心得

最经几天比较闲写了一个基于Tcp网络通信的聊天程序,写的过程中实现了文件传输,可是却怎样也无法将文件名传送过去,期间想过用通信的端口发送文件的名称,但是又要自己定义一个协议,觉得那样比较麻烦,于是想到了Remoting。

于是就开始了Remoting的研究之路 ,只是简单的用了一下,也只是入门希望可以帮助到刚入门Remoting的同学们。

在这里我写了一个模板类 ,你们拿去可以直接使用 废话不多说了 全是干货。

这是一个自己写的一个模版类

 using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp; namespace NetChatLib
{
/// <summary>
/// 用于Remoting的连接与释放
/// </summary>
public class Remoting_Helper
{
/// <summary>
/// 服务端激活Remoting
/// </summary>
/// <typeparam name="T">类的类型</typeparam>
/// <param name="port">端口号</param>
/// <returns></returns>
public bool Serivce<T>(int port)
{
//这里将通过反射获取T的类型的字符串
T type = (T)Activator.CreateInstance(typeof(T));
//这里需要注意子类即使重写了GetType 也不行
//系统调用的仍然是Object的GetTtpe
string str = type.GetType().ToString();
str = str.Split('.')[];
try
{
TcpServerChannel chnl = new TcpServerChannel("talkChannel", port);
ChannelServices.RegisterChannel(chnl, true);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(T), str, WellKnownObjectMode.SingleCall);
return true;
}
catch
{
return false;
} }
/// <summary>
/// 客户端激活Remoting
/// </summary>
/// <typeparam name="T">类的类型</typeparam>
/// <param name="url">类型所在宿主位置</param>
/// <returns>该类的实例</returns>
public T Client<T>(string url)
{
try
{
TcpClientChannel chnl = new TcpClientChannel();
ChannelServices.RegisterChannel(chnl, true);
T cls = (T)Activator.GetObject(typeof(T), url);
return cls; }
catch
{
return default(T);
} }
}
}

这是使用的方法

客户端  DemoClass是我测试的一个类

 static void Main(string[] args)
{
string url = "tcp://172.16.22.22:12346/DemoClass";
DemoClass cls = new Remote_help().Client<DemoClass>(url);
cls.SetName("你好世界");
Console.Read();
}

服务器端

 static void Main(string[] args)
{
new Remote_help().Serivce<DemoClass>();
Console.WriteLine("服务开启");
Console.ReadKey();
Console.WriteLine(new DemoClass().GetName());
Console.ReadKey();
}

我的DemoClass测试类

 public class DemoClass : MarshalByRefObject
{
private int count = ;
private static string name; public void SetName(string name)
{
DemoClass.name = name;
}
public string GetName()
{
return DemoClass.name;
} public DemoClass()
{
Console.WriteLine("------DemoClassConstructor-------");
}
public void showCount(string name)
{
count++;
Console.WriteLine("{0} The Count is {1}", name, count);
}
public void showAppDomain()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
Console.WriteLine(currentDomain.FriendlyName);
}
public int GetCount()
{
return count;
}
}

最近使用发现了一个问题 :在不同计算机上启动Remoting服务失败的结果

解决方法:将ChannelServices.RegisterChannel(chnl, true);true 改为false

如果还是不行,就换Http协议进行传输就好了