新建一个类库作为RemotingObject
新建一个Form工程作为Server。
开发时候,我觉这个问题好奇怪,默认建立的Server工程里可以直接using System.Runtime.Remoting,问题是代码里并不能提供HttpChannel的智能提示,解决办法是添加引用 System.Runtimg.Remoting这个DLL到工程里就可以了。
RemoteObject
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RemoteObject
{
public class MyObject : MarshalByRefObject
{
public int Add(int a, int b)
{
return a + b;
}
}
}
服务端
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.runtime.remoting>
<application name="RemoteServer">
<service>
<wellknown type="RemoteObject.MyObject,RemoteObject" objectUri="RemoteObject.MyObject"
mode="Singleton" />
</service>
<channels>
<channel ref="tcp" port="9999"/>
</channels>
</application>
</system.runtime.remoting>
</configuration>
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
namespace RemoteServer
{
class Program
{
static void Main(string[] args)
{
//RemoteServer.exe.config文件在调试运行时会自动生成,名字就是程序名字+.exe+.config.
//RemotingConfiguration 这句起作用了
RemotingConfiguration.Configure("RemoteServer.exe.config",false); //第二个参数如果写成true,客户端可能会卡死
//RemotingConfiguration.Configure("RandomName.exe.config", false); //报错,应用程序名字不是RandomName,而是RemoteServer
Console.ReadLine();
}
}
}
客户端
Form1.cs
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 System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
namespace RemotingClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//RemoteObject.MyObject rm = new RemoteObject.MyObject(); //本地调用
//button1.Text = rm.Add(1, 2).ToString();
System.Runtime.Remoting.Channels.Tcp.TcpChannel tcp = new System.Runtime.Remoting.Channels.Tcp.TcpChannel();
ChannelServices.RegisterChannel(tcp, false);
RemotingConfiguration.RegisterWellKnownClientType(typeof(RemoteObject.MyObject), "tcp://localhost:9999/RemoteObject.MyObject");
RemoteObject.MyObject rm = new RemoteObject.MyObject();
int result = rm.Add(33, 121);
button1.Text = result.ToString();
}
}
}
浙公网安备 33010602011771号