private void ReceiveResponse(out RtspResponse response) { response = null; var responseBytesCount = 0; byte[] responseBytes = new byte[1024]; try { responseBytesCount = _rtspSocket.Receive(responseBytes, responseBytes.Length, SocketFlags.None); response = RtspResponse.Deserialise(responseBytes, responseBytesCount); string contentLengthString; int contentLength = 0; if (response.Headers.TryGetValue("Content-Length", out contentLengthString)) { contentLength = int.Parse(contentLengthString); if ((string.IsNullOrEmpty(response.Body) && contentLength > 0) || response.Body.Length < contentLength) { if (response.Body == null) { response.Body = string.Empty; } while (responseBytesCount > 0 && response.Body.Length < contentLength) { responseBytesCount = _rtspSocket.Receive(responseBytes, responseBytes.Length, SocketFlags.None); response.Body += System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytesCount); } } } } catch (SocketException) { } }
/// <summary> /// Send an RTSP request and retrieve the response. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> /// <returns>the response status code</returns> public RtspStatusCode SendRequest(RtspRequest request, out RtspResponse response) { response = null; lock (_lockObject) { NetworkStream stream = null; try { stream = _client.GetStream(); if (stream == null) { throw new Exception(); } } catch { _client.Close(); } try { if (_client == null) { _client = new TcpClient(_serverHost, 554); } // Send the request and get the response. request.Headers.Add("CSeq", _cseq.ToString(CultureInfo.InvariantCulture)); byte[] requestBytes = request.Serialise(); stream.Write(requestBytes, 0, requestBytes.Length); _cseq++; byte[] responseBytes = new byte[_client.ReceiveBufferSize]; int byteCount = stream.Read(responseBytes, 0, responseBytes.Length); response = RtspResponse.Deserialise(responseBytes, byteCount); // Did we get the whole response? string contentLengthString; int contentLength = 0; if (response.Headers.TryGetValue("Content-Length", out contentLengthString)) { contentLength = int.Parse(contentLengthString); if ((string.IsNullOrEmpty(response.Body) && contentLength > 0) || response.Body.Length < contentLength) { if (response.Body == null) { response.Body = string.Empty; } while (byteCount > 0 && response.Body.Length < contentLength) { byteCount = stream.Read(responseBytes, 0, responseBytes.Length); response.Body += System.Text.Encoding.UTF8.GetString(responseBytes, 0, byteCount); } } } return(response.StatusCode); } finally { stream.Close(); } } }