启动对应的是OnStart
停止对应的是OnStop
下面是如何启动一个服务,本次例子服务是写一个服务端的socket通信
protected override void OnStart(string[] args)
{
serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any;
IPEndPoint point = new IPEndPoint(ip, 8978);
//socket绑定监听地址
serverSocket.Bind(point);
//Console.WriteLine("Listen Success");
//设置同时连接个数
serverSocket.Listen(10);
//利用线程后台执行监听,否则程序会假死
Thread thread = new Thread(Listen);
thread.IsBackground = true;
thread.Start(serverSocket);
Log.WriteLog(Log.LogLevel.INFO, "Listen:", "Start");
}
/// <summary>
/// 监听连接
/// </summary>
/// <param name="o"></param>
static void Listen(object o)
{
var serverSocket = o as Socket;
while (true)
{
//等待连接并且创建一个负责通讯的socket
var send = serverSocket.Accept();
//获取链接的IP地址
var sendIpoint = send.RemoteEndPoint.ToString();
Log.WriteLog(Log.LogLevel.INFO, "Connected:", sendIpoint.ToString());
//开启一个新线程不停接收消息
Thread thread = new Thread(Recive);
thread.IsBackground = true;
thread.Start(send);
}
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="o"></param>
static void Recive(object o)
{
try
{
var send = o as Socket;
while (true)
{
//获取发送过来的消息容器
byte[] buffer = new byte[1024 * 1024 * 2];
var effective = send.Receive(buffer);
//Log.WriteLog(Log.LogLevel.INFO, "RemoteEndPoint:", send.RemoteEndPoint.ToString());
//有效字节为0则跳过
if (effective == 0)
{
Log.WriteLog(Log.LogLevel.INFO, "effective", effective.ToString());
break;
}
var str = Encoding.UTF8.GetString(buffer, 0, effective);
if (!str.Equals("[S]HeartBeat[E]"))
Log.WriteLog(Log.LogLevel.INFO, "received:", str + send.RemoteEndPoint.ToString());
//Console.WriteLine(str);
DevComm.sendSocket = send;
string strRet = devComm.CommandProc(str, send);
//if (!str.Equals("[S]HeartBeat[E]"))
// Log.WriteLog(Log.LogLevel.INFO, "received:", str + send.RemoteEndPoint.ToString() + " return ");
//var buffers = Encoding.UTF8.GetBytes(strRet);
//Log.WriteLog(Log.LogLevel.INFO, "Send:", strRet);
//send.Send(buffers);
}
}
catch (Exception e)
{
Log.WriteLog(Log.LogLevel.ERROR, "Connected:", "Disconnected" + e.Message.ToString());
try
{
if (IsExistsService(serviceName))
{
LaunchService(serviceName);
}
Log.WriteLog(Log.LogLevel.INFO, "服务遇到异常后重新启动成功:", e.Message.ToString());
}
catch (Exception ex)
{
Log.WriteLog(Log.LogLevel.INFO, "服务遇到异常后重新启动失败:", ex.Message.ToString());
}
}
}
下面是如何暂停方法,暂停和停止都要先判断该服务是否存在
protected override void OnStop()
{
serverSocket.Close();
Log.WriteLog(Log.LogLevel.INFO, "服务停止状态", "开始");
try
{
if (IsExistsService(serviceName))
{
StopService(serviceName);
}
Log.WriteLog(Log.LogLevel.INFO, "服务停止状态", "成功");
}
catch (Exception ex)
{
Log.WriteLog(Log.LogLevel.INFO, "服务停止状态", "失败" + ex.Message.ToString());
}
}
#region 判断服务是否存在
private static bool IsExistsService(string serviceName)
{
/* 另一种方法
得到当前计算机所有服务对象
serviceController[] serviceControllers = ServiceController.GetServices();
通过服务名【ServiceName】(非显示服务名DisplayServiceName) 得到服务对象①
ServiceController serviceController = serviceControllers.SingleOrDefault(s => s.ServiceName == serviceName);
*/
foreach (ServiceController sc in ServiceController.GetServices())
{
if (sc.ServiceName.ToUpper() == serviceName.ToUpper())
{
return true;
}
}
return false;
}
#endregion
#region
private static void InstallService(string serviceProgramPath)
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceProgramPath;
IDictionary saveState = new Hashtable();
installer.Install(saveState);
installer.Commit(saveState);
}
}
#endregion
#region 启动服务
private static void LaunchService(string serviceName)
{
using (ServiceController currentService = new ServiceController(serviceName))
{
if (currentService.Status == ServiceControllerStatus.Stopped)
{
currentService.Start();
}
}
}
#endregion
#region 停止服务
private void StopService(string serviceName)
{
using (ServiceController service = new ServiceController(serviceName))
{
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
}
}
}
#endregion
service对应的是服务名称,startType可以设置服务的启动类型