职业IT人-IT人生活圈

 找回密码
 成为会员
搜索
查看: 1279|回复: 0

在 windows 服务中驻留远程对象

[复制链接]
梦段桥 发表于 2007-8-30 13:57 | 显示全部楼层 |阅读模式
在windows 服务中驻留远程对象:

因为控制台应用程序不能由windows服务提供,因此不要尝试读取或写入到控制台。可以使用windows服务向文件或者事件日志发送跟踪或错误消息。System.Diagnostics.EventLog类提供了对windows事件日志读写的方法。

下面是远程对象使用的程序集: MathLibrary.dll

using System;
using System.Runtime.Remoting;
using System.Diagnostics;
namespace MathLibrary
{
/// <summary>
/// SimpleMath 的摘要说明。
/// </summary>
public class SimpleMath : MarshalByRefObject
{
public SimpleMath()
{
  WriteLogEntry(\"SimpleMath actor called\");                                       
}
public int Add(int n1,int n2)
{
  WriteLogEntry(string.Format(\"SimpleMath.Add({0},{1})\",n1,n2));              return n1 + n2;
}
public int Subtract(int n1,int n2)
{
  WriteLogEntry(string.Format(\"SimpleMath.Subtract({0},{1})\",n1,n2));          return n1 - n2;
}
public void WriteLogEntry(string msg){
  EventLog.WriteEntry(\"MathService\",msg);
}
}
}

建立windows服务:

新建立一个windows服务项目,命名为 MathService,下面是OnStart()方法中的对远程对象的注册:

protected override void OnStart(string[] args)
{
  HttpChannel channel = new HttpChannel(13101);
  ChannelServices.RegisterChannel(channel);
  RemotingConfiguration.RegisterWellKnownServiceType(typeof(MathLibrary.SimpleMath),\"SimpleMath.soap\",WellKnownObjectMode.Singleton);
}

通过Installutil.exe可以安装或卸载windows服务。

Installutil directory\\MathService.exe //安装
Installutil directory\\MathService.exe //卸载

启动windows服务后,可以利用下面的客户端测试,同时,可以在事件查看器中查看相应的消息。

客户端程序:
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;

using MathLibrary;
namespace MathClient
{
/// <summary>
/// ClientMain 的摘要说明。
/// </summary>
class ClientMain
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
  HttpChannel channel = new HttpChannel();
  ChannelServices.RegisterChannel(channel);

  object remoteObj = Activator.GetObject(typeof(MathLibrary.SimpleMath),\"http://localhost/13101/SimpleMath.soap\");
  SimpleMath math = (SimpleMath)remoteObj;

  do{
  Console.WriteLine(\" 5 + 2 = {0}\",math.Add(5,2));
  Console.WriteLine(\" 5 - 2 = {0}\",math.Subtract(5,2));
  }while(Console.ReadLine() != \"q\");

  Console.WriteLine(\"ress Enter to end\");
  Console.ReadLine();
}
}
}
您需要登录后才可以回帖 登录 | 成为会员

本版积分规则

QQ|手机版|小黑屋|网站帮助|职业IT人-IT人生活圈 ( 粤ICP备12053935号-1 )|网站地图
本站文章版权归原发布者及原出处所有。内容为作者个人观点,并不代表本站赞同其观点和对其真实性负责,本站只提供参考并不构成任何投资及应用建议。本站是信息平台,网站上部分文章为转载,并不用于任何商业目的,我们已经尽可能的对作者和来源进行了通告,但是能力有限或疏忽造成漏登,请及时联系我们,我们将根据著作权人的要求立即更正或者删除有关内容。

GMT+8, 2024-5-16 07:14 , Processed in 0.114319 second(s), 20 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表