Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions OPFService/NetworkService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
namespace OPFService {
class NetworkService {
OPFDictionary dict;
Socket listener;
int restarted = 0;

public NetworkService(OPFDictionary d) {
dict = d;
Expand All @@ -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
}
}
}

Expand All @@ -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)
{
}
}
}
}
11 changes: 10 additions & 1 deletion OPFService/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
namespace OPFService {
class OPFService : ServiceBase {
Thread worker;
NetworkService svc;

public OPFService() {
}
Expand All @@ -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();
}

Expand Down