private void FinalizeConnection(ClientMetadata client) { #region Add-to-Client-List if (!AddClient(client)) { Log("*** FinalizeConnection unable to add client " + client.IpPort); client.Dispose(); return; } // Do not decrement in this block, decrement is done by the connection reader int activeCount = Interlocked.Increment(ref _ActiveClients); #endregion #region Start-Data-Receiver Log("*** FinalizeConnection starting data receiver for " + client.IpPort + " (now " + activeCount + " clients)"); if (_ClientConnected != null) { Task.Run(() => _ClientConnected(client.IpPort)); } Task.Run(async() => await DataReceiver(client)); #endregion }
private async Task DataReceiver(ClientMetadata client) { try { #region Wait-for-Data while (true) { try { if (!IsConnected(client)) { break; } byte[] data = await MessageReadAsync(client); if (data == null) { // no message available await Task.Delay(30); continue; } if (_MessageReceived != null) { Task <bool> unawaited = Task.Run(() => _MessageReceived(client.IpPort, data)); } } catch (Exception) { break; } } #endregion } finally { int activeCount = Interlocked.Decrement(ref _ActiveClients); RemoveClient(client); if (_ClientDisconnected != null) { Task <bool> unawaited = Task.Run(() => _ClientDisconnected(client.IpPort)); } Log("*** DataReceiver client " + client.IpPort + " disconnected (now " + activeCount + " clients active)"); client.Dispose(); } }