private void CommunicationThread() { var buffer = new byte[BufferSize]; var polltime = StatePollingMinTime; var adjpolltime = 0; var response = _tunnel.Connect(new ConnectRequest(_sid, _address, _port)); Log(response.Message, ESeverity.INFO); if (!response.Success) { return; } _cid = response.Cid; while (!_mre.WaitOne(WaitTime(polltime, adjpolltime), false)) { var startmarker = DateTime.Now; var isConnected = false; var isDataAvailAble = false; try { isConnected = !(_client.Client.Poll(SocketTestPollingTime, SelectMode.SelectRead) && _client.Client.Available == 0); isDataAvailAble = _stream.DataAvailable; } catch (Exception ex) { HandleError(ex, false); } if (isConnected) { if (isDataAvailAble) { var count = 0; try { count = _stream.Read(buffer, 0, BufferSize); } catch (Exception ex) { HandleError(ex, true); } if (count > 0) { var transBuffer = new byte[count]; Array.Copy(buffer, transBuffer, count); Shared.Runtime.Program.StaticXorEncoder(ref transBuffer, _cid); IConnectionContextResponse writeResponse = _tunnel.Write(new WriteRequest(_sid, _cid, transBuffer)); if (writeResponse.Success) { HandleState(writeResponse); } else { HandleError(writeResponse); } polltime = StatePollingMinTime; } } else { polltime = Convert.ToInt32(Math.Round(StatePollingFactor * polltime)); polltime = Math.Min(polltime, StatePollingMaxTime); } var readResponse = _tunnel.Read(new ConnectionContextRequest(_sid, _cid)); if (readResponse.Success) { if (readResponse.Connected && readResponse.DataAvailable) { var result = readResponse.Data; Shared.Runtime.Program.StaticXorEncoder(ref result, _cid); try { _stream.Write(result, 0, result.Length); } catch (Exception ex) { HandleError(ex, true); } polltime = StatePollingMinTime; } else { HandleState(readResponse); } } else { HandleError(readResponse); } } else { _mre.Set(); } adjpolltime = Convert.ToInt32(DateTime.Now.Subtract(startmarker).TotalMilliseconds); } Disconnect(); }