using System; using System.Net.Sockets; using System.Threading.Tasks; using System.Net; using SBRL.Utilities; using System.IO; namespace PixelServer { /// /// Provides the server component of the Hull Pixelbot server that can be used to control any number of pixel bots at once. /// public class PixelServer { TextWriter logger; IPAddress bindAddress = IPAddress.Any; int port; TcpListener server; /// /// Whether the Hull Pixelbot serve is currently active and listening. /// 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 PixelServer(int inPort, TextWriter inLogger) { Port = inPort; logger = inLogger; } public PixelServer(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); 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()); } } Console.WriteLine("Lost connection from {0}.", client.Client.RemoteEndPoint); } } }