57 lines
1.5 KiB
C#
57 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.IO.Pipes;
|
|
|
|
namespace BotBridge;
|
|
|
|
internal class BotExtPipe
|
|
{
|
|
private readonly NamedPipeServerStream _pipeServerStream;
|
|
|
|
public BotExtPipe(string pipeName)
|
|
{
|
|
_pipeServerStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
|
|
}
|
|
|
|
public void WaitForConnection()
|
|
{
|
|
_pipeServerStream.WaitForConnection();
|
|
}
|
|
|
|
public byte[] ReadData()
|
|
{
|
|
int messageLength = BitConverter.ToInt32(ReadBytes(_pipeServerStream, 4), 0);
|
|
return ReadBytes(_pipeServerStream, messageLength);
|
|
}
|
|
|
|
public void WriteData(byte[] data)
|
|
{
|
|
byte[] dateLength = BitConverter.GetBytes(data.Length);
|
|
_pipeServerStream.Write(dateLength, 0, dateLength.Length);
|
|
_pipeServerStream.Write(data, 0, data.Length);
|
|
}
|
|
|
|
|
|
private static byte[] ReadBytes(NamedPipeServerStream pipeServerStream, int bytesToRead)
|
|
{
|
|
byte[] buffer = new byte[bytesToRead];
|
|
int bytesRead = 0;
|
|
int totalBytesRead = 0;
|
|
do
|
|
{
|
|
bytesRead = pipeServerStream.Read(buffer, totalBytesRead, bytesToRead - totalBytesRead);
|
|
totalBytesRead += bytesRead;
|
|
} while (bytesRead > 0 && totalBytesRead < bytesToRead);
|
|
return buffer;
|
|
}
|
|
|
|
public void Close()
|
|
{
|
|
_pipeServerStream.Close();
|
|
}
|
|
|
|
}
|