问题描述:由于最近项目需要使用Mac地址与注册码进行加密处理,但是又因为Web程序的局限性不能获取客户端电脑系统信息,当然IE浏览器有一个activex控件他是可以通过Js在前端代码中直接获取的,局限性太小放弃。我的实现方法是通过windows服务嵌套一个HttpService服务实现。本人初级菜鸟希望有大佬看到能有多多指教,同时也记录下来加深自己的印象。大概实现步骤如下
一 创建一个winform项目
二 在根目录下创建一个windowsService服务名称随意,本文中取得是Service1
public partial class Service1 : ServiceBase { System.Threading.Timer recordTimer;
public Service1() { InitializeComponent(); }
/// /// 服务开启 /// /// protected override void OnStart(string[] args) { //获取Mac地址与注册码本地接口Http接口嵌入也可在增加其他业务代码
HttpServer httpServer; if (args.GetLength(0) > 0) { httpServer = new MyHttpServer(Convert.ToInt16(args[0])); } else {
//日志文件记录 FileOpetation.SaveRecord(string.Format(@"当前记录时间:{0},状况:启动服务!", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));
//爆的本机端口尽量用大的数字不要使用1433一下数字作为端口 httpServer = new MyHttpServer(8888); } //操作线程方法 Thread thread = new Thread(new ThreadStart(httpServer.listen)); thread.Start(); }
//停止服务
protected override void OnStop() { if (recordTimer != null) { recordTimer.Dispose(); } }
三 创建一个服务类 实现.net框架的类HttpListener。以下为简介代码返回数据格式需要自行处理另外会存在一个跨域问题,代码包中有注解 - public class MyHttpServer : HttpServer {
- public MyHttpServer(int port)
- : base(port) {
- }
- public override void handleGETRequest(HttpProcessor p) {
- Console.WriteLine("request: {0}", p.http_url);
- p.writeSuccess();
- p.outputStream.WriteLine("<html><body><h1>test server</h1>");
- p.outputStream.WriteLine("Current Time: " + DateTime.Now.ToString());
- p.outputStream.WriteLine("url : {0}", p.http_url);
-
- p.outputStream.WriteLine("<form method=post action=/form>");
- p.outputStream.WriteLine("<input type=text name=foo value=foovalue>");
- p.outputStream.WriteLine("<input type=submit name=bar value=barvalue>");
- p.outputStream.WriteLine("</form>");
- }
-
- public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData) {
- Console.WriteLine("POST request: {0}", p.http_url);
- string data = inputData.ReadToEnd();
-
- p.outputStream.WriteLine("<html><body><h1>test server</h1>");
- p.outputStream.WriteLine("<a href=/test>return</a><p>");
- p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data);
- }
- }
复制代码四 添加一个安装程序类

大概步骤已经完成了剩下就是打包发布 源码下载链接 https://files.cnblogs.com/files/pengdakun/MyFirstWindowsService.rar
打包好程序下载链接 https://files.cnblogs.com/files/pengdakun/%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.rar
|