Connection
A class in Root.Township, Alta.Networking.
One network link between the server and a client: per channel send queues, receivers and a table of message handlers. The server has one per connected client (Player.ConnectionToRemotePlayer); a client has one to the server.
- Listed in Networking and servers
- Inherits or implements
IConnection - Documented in Sockets and connections
Constructors
| Member | What it is |
|---|---|
Connection(ISocket socket, ITransportConnection connection, string ipAddress, ConnectionChannel[] channels) | Creates a Connection from socket, connection, ipAddress and channels. |
Fields
17 private and internal fields
| Member | What it is |
|---|---|
private ConnectionChannel[] channels | The channels this connection was created with; each has a packet manager and a receiver. |
private CancellationTokenSource clientPauseDisconnectCancel | Cancels the pending pause timeout when the client resumes or pauses again. |
private readonly string IpAddress | Remote IP address, used by Ping. |
private bool isDisposed | Backing field for IsDisposed; once set, Send does nothing. |
private bool isFlooded | Not used in this class. |
private bool isQueueLimitWarned | Set after the queue limit warning is logged, so it is logged once until the queue recovers. |
private bool IsQueuingSends | While set (between StartQueuing and StopQueuing), sends are held in each channel's queue instead of going out. |
private static readonly Logger logger | NLog logger for this class. |
private readonly int MaxConnectionQueueSize | Per-connection outgoing queue limit from NetworkingSettings; sends are dropped once the transport queue reaches it. |
private readonly int MaxServerQueueSize | Socket-wide outgoing queue limit from NetworkingSettings; sends on any connection are dropped once it is reached. |
private readonly Dictionary<MessageType, SerializeConnectionMethod> messageHandlers | Handlers for incoming messages, keyed by message type; set with SetHandler. |
private readonly List<OutgoingPacketManager> outgoingPacketManagers | One outgoing packet manager per channel, updated and flushed each frame. |
private int outgoingQueueSize | Transport outgoing queue size read in UpdatePacketManagers, compared with MaxConnectionQueueSize. |
private readonly Dictionary<ConnectionChannel, OutgoingPacketManager> packetManagerMap | Outgoing packet manager for each channel, used by Send. |
private IPlayer player | Backing field for Player. |
private readonly Dictionary<int, ConnectionReceiver> receivers | Incoming message receiver for each channel identifier. |
private static readonly object sendLock | Static lock held around each transport send. |
Properties
| Member | What it is |
|---|---|
ConnectionChannel DefaultChannel { get; set; } | Channel used when a send passes a null channel. |
int Identifier { get; } | The transport connection id. |
bool IsApproved { get; private set; } | Whether the connection has been approved. Sends still queue before this, but nothing is flushed. |
bool IsDisposed { get; } | True once Dispose has run. Sends then return false. |
IPlayer Player { get; set; } | The IPlayer on the other end. Setting it updates PlayerName and raises PlayerSet. |
string PlayerName { get; private set; } | Username of the linked player, or Unknown Player before one is set. |
ISocket Socket { get; private set; } | The ISocket this connection belongs to. |
UserInfoAndRole UserInfo { get; set; } | The user and role info for the player on this connection. |
1 private and internal property
| Member | What it is |
|---|---|
private ITransportConnection TransportConnection { get; } | The underlying transport connection that packets are sent and received through. |
Events
| Member | What it is |
|---|---|
event ConnectionEventHandler Approved | Raised when the connection is approved. |
event ConnectionEventHandler Disconnected | Raised when the connection is disposed while the transport is running. Exceptions in handlers are logged. |
event PacketSentHandler PacketSent | Raised after each packet goes to the transport, with its bytes, channel and result. |
event Action<IPlayer> PlayerSet | Raised when Player is assigned. |
Methods
| Member | What it is |
|---|---|
void Approve() | Marks the connection approved and raises Approved. Packets are only flushed once approved. |
void ClearAllHandlers() | Removes every message handler. |
void ClearHandler(MessageType message) | Removes the handler for one message type. |
void Disconnect(string reason) | Logs the reason, clears approval and asks the socket to close the connection. |
void Dispose() | Sends the transport disconnect, raises Disconnected and frees queues, receivers and handlers. Safe to call twice. |
void FlushPacketManagers() | Sends everything waiting in each channel's outgoing packet manager. Does nothing until approved. |
IEnumerator Ping(Action<float> callback, float timeOut = 5) | Coroutine that pings the remote IP address and passes the time to the callback. |
void ProcessExistingQueues() | Has each channel's receiver process the messages it has queued. |
void ReceivePacket(int channelIdentifier, ArraySegment<byte> data) | Hands an incoming packet to the receiver for its channel. |
void ReceivePacketOnServer(ArraySegment<byte> data) | Processes every message in a packet straight away, one after another. |
bool Send(ConnectionChannel channel, MessageType type, SerializeConnectionMethod handler) | Queues a message (or raw writer bytes) on a channel's outgoing packet manager. Returns false if disposed or the channel is unknown. |
bool Send(ConnectionChannel channel, StreamWriter writer, int byteCount) | Queues a message (or raw writer bytes) on a channel's outgoing packet manager. Returns false if disposed or the channel is unknown. |
void SetHandler(MessageType message, SerializeConnectionMethod handler) | Sets the handler for a message type on this connection, warning if it replaces one. |
void StartQueuing() | Holds outgoing messages instead of sending them. Used while a client reports it has paused; a client paused for a minute is disconnected. |
void StopQueuing() | Stops holding messages and sends everything that was queued. |
override string ToString() | The user info if known, otherwise the connection id. |
void UpdatePacketManagers() | Per frame update of the outgoing packet managers, reading the transport queue size first. Does nothing until approved. |
8 private and internal methods
| Member | What it is |
|---|---|
private async void DisconnectAfterTimeout(Connection connection) | Server: started when a client pauses; disconnects it with "Pause Timeout" after one minute unless the pause ends first. |
internal void HandleConnectionPause(Connection connection, Stream stream) | Server: handler for ConnectionPauseRequest. A pausing client has its sends queued and gets a one minute disconnect timer; resuming flushes the queue. |
private bool HasHandler(MessageType message) | True if a handler is set for the message type; SetHandler uses it to warn about overriding. |
internal bool InternalSend(byte[] data, int byteCount, ConnectionChannel channel, out INetworkTransportResult result, out bool isErrorSilent) | Sends packet bytes through the transport on a channel, unless the transport isn't started or a queue limit is hit. Updates packet counters and raises PacketSent. |
private void OnApproved() | Raises Approved; called once from Approve. |
private void OnDisconnected() | Raises Disconnected, logging any error a listener throws; called from Dispose. |
private bool QueueLimitReached() | True when the transport reports flooding or the socket or connection queue limit is hit. Logs a warning once until the queue recovers. |
internal bool TryGetMessageHandler(MessageType type, out SerializeConnectionMethod handler) | Looks up the handler set for a message type; used by MessageProcessor when a message arrives. |
Used in
Members of other types that take, return or hold a Connection:
ChunkSync.disconnectedConnections, ChunkSync.RemoveSync, ForestGenerator.Connection, ConfirmJoinMessage.Serialize, ConnectionChannel.CreateConnectionReceiver, ConnectionEventHandler.BeginInvoke, ConnectionEventHandler.Invoke, DestroyMessage.Serialize, EntitySerializationMessage.Serialize, EntitySyncMessage.Serialize, FakeSocket.Connections, FakeSocket.CreateConnection, FakeSocket.DestroyConnection, FakeSocket.GetConnection, INetworkSceneInternal.AddConnection, INetworkSceneInternal.Connections, ConnectionReceiver.connection, ConnectionReceiver.ConnectionReceiver, CountedQueuedConnectionReceiver.CountedQueuedConnectionReceiver, MessageProcessor.HandleMessage, MessageProcessor.ProcessSingleMessageFromData, NormalConnectionReceiver.NormalConnectionReceiver, OutgoingPacketManager.Connection, OutgoingPacketManager.OutgoingPacketManager, OutgoingPacketManager.SerializeToWriter, OutgoingPacketManager.StartSerialize, OutgoingPacketManager.StopSerialize, Packet.Send, QueuedConnectionReceiver.QueuedConnectionReceiver, SceneSerializer.connections, SceneSerializer.SerializeRead, SceneSerializer.SerializeWrite, TimedQueuedConnectionReceiver.TimedQueuedConnectionReceiver, ISocket.Connections, ISocket.CreateConnection, ISocket.DestroyConnection, ISocket.GetConnection, MoveMessage.Serialize, NetworkManager.SetupSendReceive, NetworkScene.AddConnection, NetworkScene.Connections, NetworkScene.RemoveConnection, PacketSentHandler.BeginInvoke, PacketSentHandler.Invoke, PingMessage.Serialize, RequestJoinMessage.Serialize, RequestServerDiagnosticsMessage.Serialize, SceneSerializationMessage.Serialize, IPlayer.ConnectionToRemotePlayer, SerializeConnectionMethod.BeginInvoke, SerializeConnectionMethod.Invoke, ServerDiagnosticsMessage.Serialize, ServerMessageReceiverPerConnection.connection, ConnectToServerUtility.SerializePause, ConnectToServerUtility.SetupConnectionToServer, JoinResult.ConnectionToServer, JoinResult.SuccessResult, ServerHandler.CheckForNoResponseFromConnectionAsync, ServerHandler.ConnectionCreated, ServerHandler.HandleConnectionsChange and 56 more.