悉野小楼

导航

C# .net Remoting最简单的例子

C# .net Remoting最简单的例子

 C# Remoting例子下载

服务端: 

using System;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
//在引用中添加
namespace RemotingTest
{
    class Program
    {    
        static void Main(string[] args)
        {
            try
            {
                TcpServerChannel server = new TcpServerChannel(4567); //端口
                ChannelServices.RegisterChannel(server, false); //注册通道
                
//客户端每次请求, Singleton是同用一个实例, singlecall是用各个实例
                
//Singleton和SingleCall都是服务端激活模式(WellKnown模式), 另外还有两种客户端激活模式
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingObj.PictureInfo), "MyRemotingService", WellKnownObjectMode.Singleton);
                Console.WriteLine("服务正常启动");
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString() + "失败了!"); }
            while (true) { }
        }
    }
}
//remoting, webservice传送的对像都要新建一个命名空间
//这个可以生成一个dll 在服务和客户端都引用
namespace RemotingObj
{
    //[Serializable]只调用方法时可写可不写, 传送对像时要写
    public class PictureInfo : MarshalByRefObject
    {
        public string GetPicinfo(string strName)
        {
            return "已返回[" + strName + "]的信息";
        }
        ////SingleCall启动例子要重写InitializeLifetimeService函数, 
        
////return null可以使各个实例一直存在 多用在聊天室客户端与服务端相连
        //public override object InitializeLifetimeService()
        
//{
        
//    return null;
        
//}
    }

} 

客户端:

 using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            ChannelServices.RegisterChannel(new TcpClientChannel(), false); //注册通道
            string strRemoteAddress = @"tcp://localhost:4567/MyRemotingService";
            RemotingObj.PictureInfo pic = (RemotingObj.PictureInfo)Activator.GetObject(typeof(RemotingObj.PictureInfo), strRemoteAddress);
            string str = pic.GetPicinfo("Mypic");
            Console.WriteLine("Remoting连结成功...\n" + str);
            Console.ReadKey();
        }
    }
}
namespace RemotingObj
{

    public class PictureInfo : MarshalByRefObject
    {
        public string GetPicinfo(string strName)
        {
            return "";
        }
    }
}

posted on 2011-12-08 17:46  悉野  阅读(975)  评论(0编辑  收藏  举报