sockscape/server/Libraries/Kneesocks/Stack.cs

76 lines
2.3 KiB
C#
Raw Normal View History

2017-04-21 21:04:03 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
2017-06-16 21:00:01 +00:00
namespace Kneesocks {
2017-05-12 21:05:18 +00:00
internal class Stack<T> where T : Connection {
2017-08-21 21:03:32 +00:00
private readonly Pool<T> PoolRef;
private readonly List<T> Clients = new List<T>();
private readonly bool RunWithNoClients;
private bool Running = true;
2017-04-21 21:04:03 +00:00
2017-08-21 21:03:32 +00:00
public bool Finished { get; private set; }
2017-05-12 21:05:18 +00:00
2017-05-11 21:03:28 +00:00
public Stack(Pool<T> poolRef, T initialConnection = null) {
PoolRef = poolRef;
2017-04-21 21:04:03 +00:00
if(initialConnection != null)
Clients.Add(initialConnection);
}
2017-05-11 21:03:28 +00:00
public Stack(Pool<T> poolRef, bool runWithNoClients, T initialConnection = null)
: this(poolRef, initialConnection)
2017-04-21 21:04:03 +00:00
{
RunWithNoClients = runWithNoClients;
}
2017-05-11 21:03:28 +00:00
public void AddClient(T client) {
2017-05-05 21:05:52 +00:00
lock(Clients) {
Clients.Add(client);
}
2017-04-21 21:04:03 +00:00
}
public int Count {
2017-05-20 23:33:39 +00:00
get => Clients.Count;
2017-04-21 21:04:03 +00:00
}
2017-05-20 23:33:39 +00:00
internal void StopThread() => Running = false;
2017-05-20 23:33:39 +00:00
private bool CheckIfConnected(T client)
=> !client.Disconnected && !client.OutsidePool;
2017-05-12 21:05:18 +00:00
2017-04-21 21:04:03 +00:00
public void ManageStack() {
while(Running && (Count > 0 || RunWithNoClients)) {
2017-05-11 21:03:28 +00:00
lock(Clients) {
for(var i = Count - 1; i >= 0 && Running; --i) {
var client = Clients[i];
2017-05-12 21:05:18 +00:00
var connected = CheckIfConnected(client);
2017-05-11 21:03:28 +00:00
if(connected) {
try {
client.Parse();
2017-05-25 21:08:21 +00:00
connected = CheckIfConnected(client);
2017-05-11 21:03:28 +00:00
} catch {
connected = false;
}
}
if(!connected) {
PoolRef.InvalidateConnection(client.Id);
Clients.RemoveAt(i);
}
}
}
2017-05-11 21:03:28 +00:00
// TODO consider changing this later
Thread.Sleep(1);
}
2017-04-21 21:04:03 +00:00
Finished = true;
PoolRef.InvalidateThread(this);
2017-04-21 21:04:03 +00:00
}
}
}