81 lines
2.6 KiB
C#
81 lines
2.6 KiB
C#
using System;
|
|
using System.Buffers;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Server.Networking;
|
|
|
|
public sealed class TcpConnection : IConnection
|
|
{
|
|
private readonly TcpClient _tcpClient;
|
|
private readonly NetworkStream _networkStream;
|
|
private volatile bool _isClosed;
|
|
|
|
public Guid Id { get; } = Guid.NewGuid();
|
|
public EndPoint? RemoteEndPoint => _tcpClient.Client.RemoteEndPoint;
|
|
public DateTime LastSeenUtc { get; private set; } = DateTime.UtcNow;
|
|
public bool IsAlive => !_isClosed && _tcpClient.Connected;
|
|
|
|
public TcpConnection(TcpClient tcpClient)
|
|
{
|
|
_tcpClient = tcpClient;
|
|
_tcpClient.NoDelay = true;
|
|
_networkStream = tcpClient.GetStream();
|
|
}
|
|
|
|
public async ValueTask<ReadOnlyMemory<byte>?> ReceiveAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
var headerBuffer = new byte[4];
|
|
|
|
// Await the framework ReadExactlyAsync (no return value)
|
|
await _networkStream.ReadExactlyAsync(headerBuffer.AsMemory(0, 4), cancellationToken);
|
|
|
|
int payloadLength =
|
|
(headerBuffer[0] << 24) |
|
|
(headerBuffer[1] << 16) |
|
|
(headerBuffer[2] << 8) |
|
|
headerBuffer[3];
|
|
|
|
if (payloadLength <= 0 || payloadLength > 4 * 1024 * 1024)
|
|
throw new InvalidOperationException("Invalid frame length.");
|
|
|
|
byte[] payloadBuffer = ArrayPool<byte>.Shared.Rent(payloadLength);
|
|
await _networkStream.ReadExactlyAsync(payloadBuffer.AsMemory(0, payloadLength), cancellationToken);
|
|
|
|
LastSeenUtc = DateTime.UtcNow;
|
|
return new ReadOnlyMemory<byte>(payloadBuffer, 0, payloadLength);
|
|
}
|
|
|
|
public async ValueTask SendAsync(ReadOnlyMemory<byte> payload, CancellationToken cancellationToken = default)
|
|
{
|
|
int length = payload.Length;
|
|
|
|
var header = new byte[4];
|
|
header[0] = (byte)((length >> 24) & 0xFF);
|
|
header[1] = (byte)((length >> 16) & 0xFF);
|
|
header[2] = (byte)((length >> 8) & 0xFF);
|
|
header[3] = (byte)(length & 0xFF);
|
|
|
|
await _networkStream.WriteAsync(header, cancellationToken);
|
|
await _networkStream.WriteAsync(payload, cancellationToken);
|
|
await _networkStream.FlushAsync(cancellationToken);
|
|
}
|
|
|
|
public ValueTask CloseAsync(string reason, CancellationToken cancellationToken = default)
|
|
{
|
|
_isClosed = true;
|
|
try { _tcpClient.Close(); } catch { }
|
|
return ValueTask.CompletedTask;
|
|
}
|
|
|
|
public ValueTask DisposeAsync()
|
|
{
|
|
_tcpClient.Dispose();
|
|
return ValueTask.CompletedTask;
|
|
}
|
|
}
|
|
|
|
|