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搭建完成。