using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace PlantBox.Shared.Communication { /// /// Wrap a to send easily, see Wiki > Protocol /// public class CommandStream { private NetworkStream _stream; /// /// Create a new /// /// A connected and valid public CommandStream(NetworkStream networkStream) { _stream = networkStream; } /// /// Read a from the stream /// /// public CommandPacket Receive() { // Length byte[] buffer = new byte[4]; _stream.Read(buffer, 0, buffer.Length); int length = BitConverter.ToInt32(buffer, 0); // Data buffer = new byte[length]; _stream.Read(buffer, 0, buffer.Length); string[] packet = Encoding.UTF8.GetString(buffer).Split('\n'); if (!Enum.TryParse(packet[0], true, out Command command)) { command = Command.Invalid; } return new CommandPacket(command, packet[1].Split(';')); } /// /// Read a from the stream asynchronously /// /// public async Task ReceiveAsync() { // Length byte[] buffer = new byte[4]; await _stream.ReadAsync(buffer, 0, buffer.Length); int length = BitConverter.ToInt32(buffer, 0); // Data buffer = new byte[length]; await _stream.ReadAsync(buffer, 0, buffer.Length); string[] packet = Encoding.UTF8.GetString(buffer).Split('\n'); if (!Enum.TryParse(packet[0], true, out Command command)) { command = Command.Invalid; } return new CommandPacket(command, packet[1].Split(';')); } /// /// Write a in the stream /// /// public void Send(CommandPacket command) { string packet = command.ToString(); byte[] data = Encoding.UTF8.GetBytes(packet); _stream.Write(BitConverter.GetBytes(data.Length), 0, 4); _stream.Write(data, 0, data.Length); } /// /// Write a in the stream asynchronously /// /// /// public async Task SendAsync(CommandPacket command) { string packet = command.ToString(); byte[] data = Encoding.UTF8.GetBytes(packet); await _stream.WriteAsync(BitConverter.GetBytes(data.Length), 0, 4); await _stream.WriteAsync(data, 0, data.Length); } } }