using System; using System.Net.Sockets; using System.Threading.Tasks; using System.IO; namespace PixelHub.Server { /// /// Provides an interface through which you can communicate with and control a Hull PixelBot. /// public class PixelBot { public bool Connected { get; private set; } = false; TcpClient client; StreamReader incoming; StreamWriter outgoing; /// /// Initializes a new instance and connects it to a Hull Pixelbot. /// /// The Tcp connection between the PixelHub server and the Hull PixelBot. public PixelBot(TcpClient inClient) { client = inClient; } /// /// Starts listening for and handling messages that come from the remote PixelBot. /// public async Task Handle() { if (Connected) throw new InvalidOperationException("Only one connection handling loop can be active at once!"); Connected = true; incoming = new StreamReader(client.GetStream()); outgoing = new StreamWriter(client.GetStream()) { AutoFlush = true }; outgoing.WriteLine("Test message!"); string nextLine; while((nextLine = await incoming.ReadLineAsync()) != null) { Console.WriteLine("Got message from client: '{0}'", nextLine.Trim()); } Connected = false; } /// /// Sends the given command to the remote PixelBot. /// /// The command to send. public async Task Send(PixelMessage command) { byte[] message = command.AsCompiledCommand(); await client.GetStream().WriteAsync(message, 0, message.Length); await client.GetStream().FlushAsync(); } } }