类库
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemoteObject
{
public class MyObject:MarshalByRefObject
{
public MyObject()
{
}
public void Add(int a, int b)
{
Console.WriteLine("========="+a+b);
}
}
}
客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RemoteObject;
using System.Configuration;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
namespace RemoteClient
{
class MyClient
{
static void Main(string[] args)
{
//声明TcpClientChannel类型的字段channels
TcpClientChannel channelc;
//声明MyObject类型的字段MyObject
MyObject remoteObject;
//创建TcpClientChannel对象,引用为channelc
channelc = new TcpClientChannel();
//将channels注册到信道服务
ChannelServices.RegisterChannel(channelc, false);
//创建远程对象
remoteObject = (MyObject)Activator.GetObject(typeof(MyObject), "tcp://127.0.0.1:3000/MyUri");
//调用服务的方法
remoteObject.Add(5, 6);
Console.WriteLine("调用成功");
Console.Read();
}
}
}
服务端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting.Channels;
using RemoteObject;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting;
namespace RemoteServer
{
class MyServer
{
static void Main(string[] args)
{
//声明TcpServerChannel类型的静态字段channels
TcpServerChannel channels;
//创建新的TcpServerChannel对象,端口号为3000,引用为channels
channels = new TcpServerChannel(3000);
//将channels注册到信道服务
ChannelServices.RegisterChannel(channels, false);
//创建知名服务类型的对象,传递远程对象的类型,对象URI和激活对象的枚举成员
RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyObject), "MyUri", WellKnownObjectMode.Singleton);
//信息提示,当用户输入字符,则结束程序
Console.WriteLine("======服务器端已启动======");
Console.Read();
}
}
}