From 23a380cd5aa3654204b7e08bda842495fa112aab Mon Sep 17 00:00:00 2001 From: Skons Date: Tue, 20 Feb 2018 20:29:36 +0100 Subject: [PATCH] OPFService now cleanly closes the socket upon exiting --- OPFService/NetworkService.cs | 39 +++++++++++++++++++++++++++++++----- OPFService/Program.cs | 11 +++++++++- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/OPFService/NetworkService.cs b/OPFService/NetworkService.cs index 454d8e5..9e97bac 100644 --- a/OPFService/NetworkService.cs +++ b/OPFService/NetworkService.cs @@ -26,6 +26,8 @@ namespace OPFService { class NetworkService { OPFDictionary dict; + Socket listener; + int restarted = 0; public NetworkService(OPFDictionary d) { dict = d; @@ -34,17 +36,32 @@ public NetworkService(OPFDictionary d) { public void main() { IPAddress ip = IPAddress.Parse("127.0.0.1"); IPEndPoint local = new IPEndPoint(ip, 5999); - Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - try { + try + { listener.Bind(local); listener.Listen(64); - while (true) { + while (true) + { Socket client = listener.Accept(); new Thread(() => handle(client)).Start(); } - } catch (Exception e) { - // don't know what to do here + } + catch (Exception e) + { + String exception = e.ToString(); + //On a not sane restart, the Socket keeps the connection up for 30 seconds + //try a restart by calling main() again + if (exception.Contains("Only one usage of each socket address") && restarted < 4) + { + restarted++; + System.Threading.Thread.Sleep(30000); + main(); + } + else { + throw; //shut the service down + } } } @@ -68,5 +85,17 @@ public void handle(Socket client) { } client.Close(); } + + public void Close() + { + restarted = 0; //reset the counter + try + { + listener.Close(); + } + catch (Exception e) + { + } + } } } diff --git a/OPFService/Program.cs b/OPFService/Program.cs index 15bc417..bfacb9c 100644 --- a/OPFService/Program.cs +++ b/OPFService/Program.cs @@ -24,6 +24,7 @@ namespace OPFService { class OPFService : ServiceBase { Thread worker; + NetworkService svc; public OPFService() { } @@ -36,13 +37,21 @@ protected override void OnStart(string[] args) { base.OnStart(args); OPFDictionary d = new OPFDictionary(AppDomain.CurrentDomain.BaseDirectory + "\\opfmatch.txt", AppDomain.CurrentDomain.BaseDirectory + "opfcont.txt"); // OPFDictionary d = new OPFDictionary("c:\\windows\\system32\\opfmatch.txt", "c:\\windows\\system32\\opfcont.txt"); - NetworkService svc = new NetworkService(d); + svc = new NetworkService(d); worker = new Thread(() => svc.main()); worker.Start(); } protected override void OnShutdown() { base.OnShutdown(); + svc.Close(); + worker.Abort(); + } + + protected override void OnStop() + { + base.OnStop(); + svc.Close(); worker.Abort(); }