C#远程调用实现案例

 C#实现远程调用主要用到“System.Runtime.Remoting”这个东西。下面从三个方面给于源码实例。

·服务端:

using  System.Runtime.Remoting.Channels;
using  System.Runtime.Remoting.Channels.Tcp;
using  System.Runtime.Remoting;

namespace  RemoteSample
{
    
class server
    
{
        
static int Main(string[] args)
        
{
            
//注册通道
            TcpChannel chan = new TcpChannel(8085);        
            ChannelServices.RegisterChannel(chan);
            
string sshan = chan.ChannelName;
            System.Console.WriteLine(sshan);
            
//注册远程对象,即激活.
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteSample.HelloServer), "SayHello", WellKnownObjectMode.SingleCall);
            System.Console.WriteLine(
"Hit <ennter> to exit...");
            System.Console.ReadLine();
            
return 0;
        }

    }

}

·客户端:

using  System.Runtime.Remoting.Channels.Tcp;
using  System.Runtime.Remoting.Channels;

namespace  RemoteSample
{
    
public class Client
    
{
        
public static int Main(string[] args)
        
{
            TcpChannel chan 
= new TcpChannel();
            ChannelServices.RegisterChannel(chan);
            HelloServer obj 
=(HelloServer)Activator.GetObject(typeof(HelloServer), "tcp://localhost:8085/SayHello");
            
if (obj == null)
                System.Console.WriteLine(
"Could   not   locate   server");
            
else Console.WriteLine(obj.HelloMethod("Caveman"));
            
return 0;   

        }


    }

}

·远程对象:(重点),该对象是一个dll的程序集,同时被客户端和服务器端引用。

namespace  RemoteSample
{
    
//客户端获取到服务端的对象实际是一个对象的引用,因此必须继承:MarshalByRefObject
    public class HelloServer : MarshalByRefObject
    
{
        
public HelloServer()
        
{
            Console.WriteLine(
"HelloServer   activated");
        }


        
public String HelloMethod(String name)
        
{
            Console.WriteLine(
"Hello.HelloMethod   :   {0}", name);
            
return "Hi there " + name;
        }


        
//说明1:在Remoting中的远程对象中,如果还要调用或传递某个对象,例如类,或者结构,则该类或结构则必须实现串行化Attribute[SerializableAttribute]:
        
//说明2:将该远程对象以类库的方式编译成Dll。这个Dll将分别放在服务器端和客户端,以添加引用
        
//说明3:在Remoting中能够传递的远程对象可以是各种类型,包括复杂的DataSet对象,只要它能够被序列化
    }

注意上述代码的注释,由于远程服务的特殊性,因此在此做了详细的批注,怕大伙不理解。

OK。C#的远程调用就实现完成了,这中应用一般在三层架构中应该比较平常使用。至于这种方式的优缺点,在下还不好说,希望有过实际应用的同志给总结一些,谢谢!!!

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值