// This file is provided under The MIT License as part of RiptideNetworking.
// Copyright (c) Tom Weiland
// For additional information please see the included LICENSE.md file or view it on GitHub:
// https://github.com/RiptideNetworking/Riptide/blob/main/LICENSE.md
using System;
using System.Net.Sockets;
namespace Riptide.Transports.Tcp
{
/// Provides base send & receive functionality for and .
public abstract class TcpPeer
{
///
public event EventHandler Disconnected;
/// An array that incoming data is received into.
internal readonly byte[] ReceiveBuffer;
/// An array that outgoing data is sent out of.
internal readonly byte[] SendBuffer;
/// The default size used for the socket's send and receive buffers.
protected const int DefaultSocketBufferSize = 1024 * 1024; // 1MB
/// The size to use for the socket's send and receive buffers.
protected readonly int socketBufferSize;
/// The main socket, either used for listening for connections or for sending and receiving data.
protected Socket socket;
/// The minimum size that may be used for the socket's send and receive buffers.
private const int MinSocketBufferSize = 256 * 1024; // 256KB
/// Initializes the transport.
/// How big the socket's send and receive buffers should be.
protected TcpPeer(int socketBufferSize = DefaultSocketBufferSize)
{
if (socketBufferSize < MinSocketBufferSize)
throw new ArgumentOutOfRangeException(nameof(socketBufferSize), $"The minimum socket buffer size is {MinSocketBufferSize}!");
this.socketBufferSize = socketBufferSize;
ReceiveBuffer = new byte[Message.MaxSize];
SendBuffer = new byte[Message.MaxSize + sizeof(int)]; // Need room for the entire message plus the message length (since this is TCP)
}
/// Handles received data.
/// The number of bytes that were received.
/// The connection from which the data was received.
protected internal abstract void OnDataReceived(int amount, TcpConnection fromConnection);
/// Invokes the event.
/// The closed connection.
/// The reason for the disconnection.
protected internal virtual void OnDisconnected(Connection connection, DisconnectReason reason)
{
Disconnected?.Invoke(this, new DisconnectedEventArgs(connection, reason));
}
}
}