sockscape/server/Libraries/Kneesocks/Stack.cs

75 lines
2.2 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;
namespace Kneesocks {
2017-05-12 21:05:18 +00:00
internal class Stack<T> where T : Connection {
private Pool<T> PoolRef = null;
2017-05-11 21:03:28 +00:00
private List<T> Clients = new List<T>();
2017-04-21 21:04:03 +00:00
private bool RunWithNoClients = false;
private bool Running = true;
2017-04-21 21:04:03 +00:00
2017-05-12 21:05:18 +00:00
public bool Finished { get; private set; } = false;
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
Thread.Sleep(10);
}
2017-04-21 21:04:03 +00:00
Finished = true;
PoolRef.InvalidateThread(this);
2017-04-21 21:04:03 +00:00
}
}
}