-
Notifications
You must be signed in to change notification settings - Fork 0
/
TcpClientConnection.cs
74 lines (58 loc) · 1.85 KB
/
TcpClientConnection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using System;
namespace Suhock.Osc;
public sealed class TcpClientConnection : IOscConnection
{
private readonly TcpClient _client;
public TcpClientConnection(TcpClient client)
{
_client = client;
}
public byte[] Receive()
{
var stream = _client.GetStream();
var sizeBytes = new byte[4];
if (stream.Read(sizeBytes, 0, 4) < 4)
{
throw new Exception();
}
var packetLength = OscUtil.ReadInt(sizeBytes, out _);
var bytesRead = 0;
var buffer = new byte[packetLength];
while (bytesRead < packetLength)
{
bytesRead += stream.Read(buffer, bytesRead, packetLength - bytesRead);
}
return buffer;
}
public async Task<byte[]> ReceiveAsync(CancellationToken cancellationToken)
{
var stream = _client.GetStream();
var sizeBytes = new byte[4];
var headerBytesRead = await stream.ReadAsync(sizeBytes.AsMemory(0, 4), cancellationToken);
if (headerBytesRead < 4)
{
throw new Exception();
}
var packetLength = OscUtil.ReadInt(sizeBytes, out _);
var bytesReadToBuffer = 0;
var buffer = new byte[packetLength];
while (bytesReadToBuffer < packetLength)
{
bytesReadToBuffer += await stream.ReadAsync(
buffer.AsMemory(bytesReadToBuffer, packetLength - bytesReadToBuffer),
cancellationToken);
}
return buffer;
}
public void Send(ReadOnlySpan<byte> data)
{
_client.GetStream().Write(data);
}
public async Task SendAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
{
await _client.GetStream().WriteAsync(data, cancellationToken);
}
}