Window服务是啥,这里就不废话了,如何用在哪里用也不废话了,这里我这篇文章只是详述了我在vs2012中创建window服务的经过,希望对你有所帮助。

另外:我在编写服务过程中参考了 Professional C# 2012 and   .NET 4.5

 

  不废话,你肯定会,会的直接去下一步。如果真的不会请继续看

  C#编写window服务,一步一步(1)

第二步添加服务用的类库项目Sensor

      并添加类文件QuoteException.cs和SensorFish.cs

  这两个类的功能并不重要,主要是给服务类用的,你也可以写自己的类文件,或者干脆不要,直接在服务类里边写逻辑代码

  QuoteException.cs代码如下:

  

C#编写window服务,一步一步(1)
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Sensor
 7 {
 8     /// <summary>
 9     /// 自定义异常
10     /// </summary>
11     [Serializable]
12     class QuoteException : Exception
13     {
14         public QuoteException() { }
15         public QuoteException(string message) : base(message) { }
16         public QuoteException(string message, Exception inner) : base(message, inner) { }
17         protected QuoteException(
18         System.Runtime.Serialization.SerializationInfo info,
19         System.Runtime.Serialization.StreamingContext context)
20             : base(info, context) { }
21     }
22 }
C#编写window服务,一步一步(1)

 

   SensorFish.cs代码如下:

  

C#编写window服务,一步一步(1)
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.IO;
  6 using System.Net;
  7 using System.Net.Sockets;
  8 using System.Threading.Tasks;
  9 using System.Diagnostics.Contracts;
 10 using System.Diagnostics;
 11 
 12 namespace Sensor
 13 {
 14     /// <summary>
 15     /// 传感器监测
 16     /// </summary>
 17     public class SensorFish
 18     {
 19 
 20 
 21         private TcpListener listener;
 22         private int port;//端口号
 23         private string filename;
 24         private List<string> quotes;
 25         private Random random;
 26         private Task listenerTask;
 27 
 28         /// <summary>
 29         /// 传感器控制类
 30         /// </summary>
 31         public SensorFish()
 32             : this("quotes.txt")
 33         {
 34 
 35         }
 36 
 37         /// <summary>
 38         /// 传感器控制类
 39         /// </summary>
 40         /// <param name="fileName"></param>
 41         public SensorFish(string fileName)
 42             : this(fileName, 7890)
 43         {
 44 
 45         }
 46 
 47         /// <summary>
 48         /// 传感器控制类
 49         /// </summary>
 50         /// <param name="fileName"></param>
 51         /// <param name="port"></param>
 52         public SensorFish(string fileName, int port)
 53         {
 54             //Contract.Requires<ArgumentNullException>(fileName != null);
 55             //Contract.Requires<ArgumentException>(port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort);
 56             this.filename = fileName;
 57             this.port = port;
 58         }
 59 
 60         protected void ReadQuotes()
 61         {
 62             try
 63             {
 64                 quotes = File.ReadAllLines(filename).ToList();
 65                 if (quotes.Count == 0)
 66                 {
 67                     throw new QuoteException("quotes  file  is   empty");
 68                 }
 69                 random = new Random();
 70             }
 71             catch (IOException ex)
 72             {
 73                 throw new QuoteException("I/O Error", ex);
 74             }
 75         }
 76 
 77         protected string GetRandomQuoteOfTheDay()
 78         {
 79             int index = random.Next(0, quotes.Count);
 80             return quotes[index];
 81         }
 82 
 83 
 84         /// <summary>
 85         /// 开启服务
 86         /// </summary>
 87         public void Start()
 88         {
 89             ReadQuotes(); //读取文件
 90             listenerTask = Task.Factory.StartNew(Listener, TaskCreationOptions.LongRunning);//异步方法调用
 91         }
 92 
 93         private void Listener()
 94         {
 95             try
 96             {
 97                 IPAddress ipAddress = IPAddress.Any;//提供一个ip地址,只是服务器应侦听所有网络接口上的客户端活动。此字段为只读
 98                 listener = new TcpListener(ipAddress, port);//指定在本地的IP地址和端口号上侦听是否有传入的连接尝试
 99                 listener.Start();//开始侦听传入的连接请求
100                 while (true)
101                 {
102                     Socket clientSocket = listener.AcceptSocket();//接受关起的连接请求
103                     string message = GetRandomQuoteOfTheDay();
104                     var encoder = new UnicodeEncoding();
105                     byte[] buffer = encoder.GetBytes(message);
106                     clientSocket.Send(buffer, buffer.Length, 0);//将指定的字节数发送到已连接的Socket
107                     clientSocket.Close();//关闭Socket,并释放所有的关联的资源
108                 }
109             }
110             catch (SocketException ex)
111             {
112                 Trace.TraceError(string.Format("QuoteServer {0}", ex.Message));
113                 throw new QuoteException("socket error", ex);
114             }
115         }
116 
117 
118         /// <summary>
119         /// 停止服务
120         /// </summary>
121         public void Stop()
122         {
123             listener.Stop();//关闭侦听
124         }
125 
126         /// <summary>
127         /// 暂定服务
128         /// </summary>
129         public void Suspend()
130         {
131             listener.Stop();
132         }
133 
134         /// <summary>
135         /// 重新开始服务
136         /// </summary>
137         public void Resume()
138         {
139             Start();
140         }
141 
142         /// <summary>
143         /// 重启
144         /// </summary>
145         public void RefreshSensor()
146         {
147             ReadQuotes();
148         }
149     }
150 }
C#编写window服务,一步一步(1)

相关文章: