sockscape/server/Libraries/Kneesocks/Server.cs

65 lines
1.8 KiB
C#
Raw Normal View History

2017-04-25 21:01:41 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
2017-05-04 12:21:27 +00:00
using System.Threading;
using System.Net.Sockets;
using System.Net;
2017-04-25 21:01:41 +00:00
2017-06-16 21:00:01 +00:00
namespace Kneesocks {
2017-06-07 21:02:29 +00:00
public abstract class Server {
protected TcpListener Socket;
protected Thread Listener = null;
public bool Started { get; protected set; } = false;
public UInt16 Port { get; protected set; }
public object Configuration { get; protected set; }
2017-05-04 12:21:27 +00:00
public void Start() {
if(!Started) {
Listener.Start();
Started = true;
}
}
public void Stop() {
if(Started) {
Started = false;
Listener.Join();
}
}
2017-06-07 21:02:29 +00:00
}
public class Server<T> : Server where T : Connection, new() {
protected Pool<T> ConnectionPool = null;
public Server(UInt16 port, Pool<T> pool, object config = null) {
Port = port;
Socket = new TcpListener(IPAddress.Any, port);
Listener = new Thread(new ThreadStart(ListenThread));
ConnectionPool = pool;
Configuration = config;
}
2017-05-04 12:21:27 +00:00
2017-06-07 21:02:29 +00:00
protected void ListenThread() {
2017-05-04 12:21:27 +00:00
Socket.Start();
while(Started) {
2017-05-12 21:05:18 +00:00
if(Socket.Pending()) {
var templatedConnection = new T() {
Server = this
};
2017-05-12 21:05:18 +00:00
templatedConnection.Initialize(Socket.AcceptTcpClient());
2017-08-16 21:01:08 +00:00
if(!ConnectionPool.AddConnection(templatedConnection))
templatedConnection.Disconnect("Connection pooler rejected connection.");
2017-05-12 21:05:18 +00:00
}
2017-05-04 12:21:27 +00:00
Thread.Sleep(100);
}
Socket.Stop();
}
2017-04-25 21:01:41 +00:00
}
}
2017-05-04 12:21:27 +00:00