Add list of current clients to PixelHub

This commit is contained in:
Starbeamrainbowlabs 2016-10-16 15:22:41 +01:00
parent 5b26c00352
commit 950d7aafa1

View file

@ -0,0 +1,101 @@
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Net;
using SBRL.Utilities;
using System.IO;
using System.Collections.Generic;
namespace PixelHub
{
/// <summary>
/// Provides the server component of the Hull Pixelbot server that can be used to control any number of pixel bots at once.
/// </summary>
public class PixelHub
{
TextWriter logger;
IPAddress bindAddress = IPAddress.Any;
int port;
TcpListener server;
List<TcpClient> clients = new List<TcpClient>();
/// <summary>
/// Whether the Hull Pixelbot serve is currently active and listening.
/// </summary>
public bool Active { get; private set; } = false;
public IPAddress BindAddress
{
get {
return bindAddress;
}
set {
if (Active == true)
throw new InvalidOperationException("Error: The bind address can't be changed once the server has started listening!");
bindAddress = value;
}
}
public int Port
{
get {
return port;
}
set {
if (Active == true)
throw new InvalidOperationException("Error: The port can't be changed once the server has started listening!");
port = value;
}
}
public IPEndPoint Endpoint
{
get {
return new IPEndPoint(BindAddress, Port);
}
}
public PixelHub(int inPort, TextWriter inLogger)
{
Port = inPort;
logger = inLogger;
}
public PixelHub(int inPort) : this(inPort, Console.Out)
{
}
public async Task Listen()
{
server = new TcpListener(Endpoint);
logger.WriteLine("TCP Listener set up on {0}.", Endpoint);
Active = true;
while(true)
{
TcpClient nextClient = await server.AcceptTcpClientAsync();
AsyncTools.ForgetTask(Handle(nextClient));
}
// TODO: Add an shutdown CancellationToken thingy here
//Active = false;
}
private async Task Handle(TcpClient client)
{
logger.WriteLine("Accepted connection from {0}.", client.Client.RemoteEndPoint);
clients.Add(client);
using (StreamReader incoming = new StreamReader(client.GetStream()))
using (StreamWriter outgoing = new StreamWriter(client.GetStream()) { AutoFlush = true })
{
string nextLine;
while((nextLine = await incoming.ReadLineAsync()) != null)
{
Console.WriteLine("Got message from client: '{0}'", nextLine.Trim());
}
}
clients.Remove(client);
Console.WriteLine("Lost connection from {0}.", client.Client.RemoteEndPoint);
}
}
}