任务:有2个客户端。它们必须压缩字节数组,发送它,接收字节数组,解压缩它并对结果做一些事情 我使用TCP进行发送和接收 解压缩方法出现错误。
发送方式:
private static void AsiooutOnAudioAvailable(object sender, AsioAudioAvailableEventArgs e)
{
audio = SamplesToBytes(monoSamples);
byte[] compressedBytes = CompressBytes(audio);
if (_isConnected)
{
Task.Run(() => _receiver.BeginSend(compressedBytes, 0, compressedBytes.Length, SocketFlags.None, SendCallback, null));
}
}
接收:
private static void Receive()
{
_receiver.BeginReceive(incomingBytes, 0, incomingBytes.Length, SocketFlags.None, ReceiveCallback, null);
}
private static void ReceiveCallback(IAsyncResult ar)
{
int receivedBytesCount = _receiver.EndReceive(ar);
byte[] _audio = new byte[receivedBytesCount];
for (int i = 0; i < receivedBytesCount; i++)
{
_audio[i] = incomingBytes[i];
}
var decompressBytes = DecompressBytes(_audio);
_incomingBuffer.AddSamples(decompressBytes, 0, decompressBytes.Length);
Receive();
}
压缩和解压缩
public static byte[] CompressBytes(byte[] bytes)
{
using (MemoryStream output = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(output, CompressionMode.Compress))
{
gzip.Write(bytes, 0, bytes.Length);
}
return output.ToArray();
}
}
static byte[] DecompressBytes(byte[] gzip)
{
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
int size = gzip.Length;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size); //error place
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}