以下是一個具有 ServiceBase 功能的 TCP Server 的 C# 範例:
using System;
using System.Net;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Threading;
namespace TCPServerExample
{
public class MyServer : ServiceBase
{
private TcpListener listener;
private bool isRunning;
public MyServer()
{
this.ServiceName = "MyTCPServer";
}
protected override void OnStart(string[] args)
{
// Start the TCP server on a separate thread
Thread serverThread = new Thread(StartServer);
serverThread.Start();
}
protected override void OnStop()
{
// Stop the TCP server
isRunning = false;
listener.Stop();
}
private void StartServer()
{
try
{
// Set the IP address and port number for the server
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 8080;
// Create a TCP listener on the specified IP address and port number
listener = new TcpListener(ipAddress, port);
listener.Start();
isRunning = true;
Console.WriteLine("Server started");
while (isRunning)
{
// Accept incoming client connections
TcpClient client = listener.AcceptTcpClient();
// Handle clients on separate threads
Thread clientThread = new Thread(HandleClient);
clientThread.Start(client);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
private void HandleClient(object clientObj)
{
TcpClient client = (TcpClient)clientObj;
try
{
// Handle client requests here
// ...
// Close the client connection
client.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
static void Main()
{
// Run the service if started from Service Control Manager
if (Environment.UserInteractive)
{
MyServer myServer = new MyServer();
myServer.OnStart(null);
Console.WriteLine("Press any key to stop the service...");
Console.ReadKey();
myServer.OnStop();
}
else
{
// Run the service normally
ServiceBase.Run(new MyServer());
}
}
}
}```
之後再寫一個bat檔, 執行後就會安裝到Service中,
例如:
@echo off
REM 取得目前 bat 檔案所在的路徑
set "current_path=%~dp0"
sc delete MyServer
REM 安裝服務
sc create MyServerbinPath= "%current_path%\MyServer.exe" start= auto
REM 設定服務自動啟動
sc config MyServer start= auto
REM 啟動服務
sc start MyServer