Add Protocol implementation
This commit is contained in:
80
PlantBox.Shared/Communication/CommandStream.cs
Normal file
80
PlantBox.Shared/Communication/CommandStream.cs
Normal file
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PlantBox.Shared.Communication
|
||||
{
|
||||
public class CommandStream
|
||||
{
|
||||
private NetworkStream _stream;
|
||||
|
||||
public CommandStream(NetworkStream networkStream)
|
||||
{
|
||||
_stream = networkStream;
|
||||
}
|
||||
|
||||
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(';'));
|
||||
}
|
||||
|
||||
public async Task<CommandPacket> 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(';'));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user