private void StartReceiveData(CancellationToken token) { while (true) { try { if (TcpClient == null || !TcpClient.Connected) { IsConnected = false; _Server.Events.HandleClientDisconnected(this, new Events.ClientDisconnectedEventArgs(Ip, Events.DisconnectReason.Timeout)); break; } if (token.IsCancellationRequested) { _Server.Events.HandleServerLog(this, new Events.ServerLoggerEventArgs(Events.LogType.ERROR, "Cancellation operation detected")); break; } DataPacket packet = ReadPacket(); if (packet == null) { continue; } _Server.Events.HandleDataReceived(this, new Events.DataReceivedFromClientEventArgs(Ip, packet.Data, packet.Header)); } catch (Exception ex) { if (ex is SocketException || ex is IOException) { _Server.Events.HandleServerLog(this, new Events.ServerLoggerEventArgs(Events.LogType.ERROR, "Data receiver socket exception (disconnection)")); IsConnected = false; _Server.DisconnectClient(Ip); return; } _Server.Events.HandleServerLog(this, new Events.ServerLoggerEventArgs(Events.LogType.EXCEPTION, "Data receiver exception", ex)); } } }
private async Task StartRecieveDataAsync(CancellationToken token) { try { while (true) { if (TcpClient == null || !TcpClient.Connected) { IsConnected = false; _Server.Events.HandleClientDisconnected(this, new Events.ClientDisconnectedEventArgs(Ip, Events.DisconnectReason.Timeout)); break; } byte[] data = await DataReadAsync(token); if (data == null) { await Task.Delay(30); continue; } if (!_IsHeaderReceived) { _Header = NormalizeRawHeader(Encoding.UTF8.GetString(data)); if (_Header.ContainsKey("Content-length")) { _IsHeaderReceived = true; _CurrentReceivingMs = new MemoryStream(); _CurrentReceivingMsSize = Convert.ToInt64(_Header["Content-length"]); } } else { _CurrentReceivingMs.Write(data); if (_CurrentReceivingMs.Length >= _CurrentReceivingMsSize) { _IsHeaderReceived = false; _Server.Events.HandleDataReceived(this, new Events.DataReceivedFromClientEventArgs(Ip, _CurrentReceivingMs.ToArray(), _Header)); _CurrentReceivingMs = null; _CurrentReceivingMsSize = 0; _Header.Clear(); } } } } catch (SocketException) { _Server.Events.HandleServerLog(this, new Events.ServerLoggerEventArgs(Events.LogType.ERROR, "Data receiver socket exception (disconnection)")); IsConnected = false; _Server.DisconnectClient(Ip); } catch (IOException) { _Server.Events.HandleServerLog(this, new Events.ServerLoggerEventArgs(Events.LogType.ERROR, "Data receiver socket exception (disconnection)")); IsConnected = false; _Server.DisconnectClient(Ip); } catch (Exception ex) { _Server.Events.HandleServerLog(this, new Events.ServerLoggerEventArgs(Events.LogType.EXCEPTION, "Data receiver exception", ex)); } }