1、服务器端使用配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.runtime.remoting>
<application>
<service>
<wellknown mode="Singleton" type="Service.Singer,Service" objectUri="Singer" ></wellknown>
</service>
<channels>
<channel ref="tcp" port="8888">
</channel>
</channels>
</application>
</system.runtime.remoting>
</configuration>
2、服务端 Host
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using Service;
namespace ServerHost
{
class Program
{
static void Main(string[] args)
{
Test2();
}
private static void Test1()
{
//创建一个通道用来公布对外的服务
TcpChannel channel = new TcpChannel(8888);
//将tcp通道通过通道服务进行注册,这里的false只的是不使用iis的安全机制
ChannelServices.RegisterChannel(channel, false);
//通过远程配置对象将要公布的对象的进行公布,包括类型uri
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Singer), "Singer", WellKnownObjectMode.Singleton);
Console.Read();
}
private static void Test2()
{
RemotingConfiguration.Configure("ServerHost.exe.config");
Console.Read();
}
}
}
3 客户端配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.runtime.remoting>
<application>
<client>
<wellknown type="Service.Singer,Service" url="tcp://localhost:8888/singer"></wellknown>
</client>
</application>
</system.runtime.remoting>
</configuration>
4 客户端调用代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Service;
using System.Runtime.Remoting;
namespace RemotingClientTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
Test2();
}
private void Test1()
{
//这里使用Activitor对象来创建远程对象的引用
Singer singer = (Singer)Activator.GetObject(typeof(Singer), "tcp://localhost:8888/Singer");
//调用远程对象的引用的方法
string content = singer.Sing("haha");
MessageBox.Show(content);
}
private void Test2()
{
RemotingConfiguration.Configure("RemotingClientTest.exe.config");
Singer singer = new Singer();
MessageBox.Show(singer.Sing("test "));
}
5、可以将被远程调用的对象封装成为接口,这样服务器端host不变但是client只能使用Activator类获得接口类了
//server接口
namespace Service
{
public interface ISinger
{
string Sing(string str);
}
}
//client
private void Test3()
{
//这里使用Activitor对象来创建远程对象的引用
ISinger singer = (ISinger)Activator.GetObject(typeof(ISinger), "tcp://localhost:8888/Singer");
//调用远程对象的引用的方法
string content = singer.Sing("haha");
MessageBox.Show(content);
}
}
}