64 lines
1.6 KiB
C#
64 lines
1.6 KiB
C#
using System;
|
|
using System.Net.Sockets;
|
|
using System.Threading.Tasks;
|
|
using System.IO;
|
|
|
|
namespace PixelHub.Server
|
|
{
|
|
/// <summary>
|
|
/// Provides an interface through which you can communicate with and control a Hull PixelBot.
|
|
/// </summary>
|
|
public class PixelBot
|
|
{
|
|
public bool Connected { get; private set; } = false;
|
|
TcpClient client;
|
|
|
|
StreamReader incoming;
|
|
StreamWriter outgoing;
|
|
|
|
/// <summary>
|
|
/// Initializes a new <see cref="PixelBot"/> instance and connects it to a Hull Pixelbot.
|
|
/// </summary>
|
|
/// <param name="inClient">The Tcp connection between the PixelHub server and the Hull PixelBot.</param>
|
|
public PixelBot(TcpClient inClient)
|
|
{
|
|
client = inClient;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Starts listening for and handling messages that come from the remote PixelBot.
|
|
/// </summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sends the given command to the remote PixelBot.
|
|
/// </summary>
|
|
/// <param name="command">The command to send.</param>
|
|
public async Task Send(PixelCommand command)
|
|
{
|
|
await outgoing.WriteLineAsync(command.AsCompiledCommand());
|
|
}
|
|
}
|
|
}
|
|
|