ConsoleServer : 创建控制台应用,把生成的ConsoleServer.exe放到桌面上的dll文件夹下。代码如下(MarshalByRefObject一定要继承,否则报异常):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleServer
{
/// <summary>
/// 业务代码
/// </summary>
public class HelloServer:MarshalByRefObject
{
public string HelloWorld(string str)
{
return "张三说: Hello" + str;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace ConsoleServer
{
class Program
{
static void Main(string[] args)
{
//创建TCP通道
TcpChannel chan = new TcpChannel(8888); //必须指定端口号
//注册通道
ChannelServices.RegisterChannel(chan, false); //借用IIS的安全机制
//加载远程对象
RemotingConfiguration.RegisterWellKnownServiceType(typeof(HelloServer), "HelloServer", WellKnownObjectMode.Singleton);
Console.Read();
}
}
}
ConsoleClient :创建控制台应用,引用桌面dll文件夹下的ConsoleServer.exe(可以当成动态库用),代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using ConsoleServer;
namespace ConsoleClient
{
class Program
{
static void Main(string[] args)
{
//建立通信通道
TcpChannel chan = new TcpChannel();
//注册通道
ChannelServices.RegisterChannel(chan, false);
HelloServer h = (HelloServer)Activator.GetObject(typeof(ConsoleServer.HelloServer),"tcp://localhost:8888/HelloServer");
string str = h.HelloWorld("aaa");
Console.WriteLine(str);
Console.ReadKey();
}
}
}
启动服务端控制台,再启动客户端程序,简单demo搭建完成。