Refactored a few for HttpListenerResponse.cs

This commit is contained in:
sta 2015-06-08 20:49:52 +09:00
parent 626e22bbcf
commit 659ab51b59
3 changed files with 33 additions and 59 deletions

View File

@ -60,7 +60,6 @@ namespace WebSocketSharp.Net
private byte[] _buffer; private byte[] _buffer;
private const int _bufferLength = 8192; private const int _bufferLength = 8192;
private bool _chunked;
private HttpListenerContext _context; private HttpListenerContext _context;
private bool _contextWasBound; private bool _contextWasBound;
private StringBuilder _currentLine; private StringBuilder _currentLine;
@ -234,7 +233,6 @@ namespace WebSocketSharp.Net
private void init () private void init ()
{ {
_chunked = false;
_context = new HttpListenerContext (this); _context = new HttpListenerContext (this);
_inputState = InputState.RequestLine; _inputState = InputState.RequestLine;
_inputStream = null; _inputStream = null;
@ -426,10 +424,7 @@ namespace WebSocketSharp.Net
var req = _context.Request; var req = _context.Request;
var res = _context.Response; var res = _context.Response;
if (req.KeepAlive && if (!res.CloseConnection && req.FlushInput ()) {
!res.CloseConnection &&
req.FlushInput () &&
(!_chunked || (_chunked && !res.ForceCloseChunked))) {
// Don't close. Keep working. // Don't close. Keep working.
_reuses++; _reuses++;
disposeRequestBuffer (); disposeRequestBuffer ();
@ -487,7 +482,6 @@ namespace WebSocketSharp.Net
var len = (int) _requestBuffer.Length; var len = (int) _requestBuffer.Length;
disposeRequestBuffer (); disposeRequestBuffer ();
if (chunked) { if (chunked) {
_chunked = true;
_context.Response.SendChunked = true; _context.Response.SendChunked = true;
_inputStream = new ChunkedRequestStream ( _inputStream = new ChunkedRequestStream (
_stream, buff, _position, len - _position, _context); _stream, buff, _position, len - _position, _context);

View File

@ -58,14 +58,13 @@ namespace WebSocketSharp.Net
private bool _chunked; private bool _chunked;
private Encoding _contentEncoding; private Encoding _contentEncoding;
private long _contentLength; private long _contentLength;
private bool _contentLengthWasSet; private bool _contentLengthSet;
private string _contentType; private string _contentType;
private HttpListenerContext _context; private HttpListenerContext _context;
private CookieCollection _cookies; private CookieCollection _cookies;
private bool _disposed; private bool _disposed;
private bool _forceCloseChunked;
private WebHeaderCollection _headers; private WebHeaderCollection _headers;
private bool _headersWereSent; private bool _headersSent;
private bool _keepAlive; private bool _keepAlive;
private string _location; private string _location;
private ResponseStream _outputStream; private ResponseStream _outputStream;
@ -97,15 +96,13 @@ namespace WebSocketSharp.Net
} }
} }
internal bool ForceCloseChunked {
get {
return _forceCloseChunked;
}
}
internal bool HeadersSent { internal bool HeadersSent {
get { get {
return _headersWereSent; return _headersSent;
}
set {
_headersSent = value;
} }
} }
@ -163,7 +160,7 @@ namespace WebSocketSharp.Net
if (value < 0) if (value < 0)
throw new ArgumentOutOfRangeException ("Less than zero.", "value"); throw new ArgumentOutOfRangeException ("Less than zero.", "value");
_contentLengthWasSet = true; _contentLengthSet = true;
_contentLength = value; _contentLength = value;
} }
} }
@ -481,7 +478,7 @@ namespace WebSocketSharp.Net
if (_disposed) if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ()); throw new ObjectDisposedException (GetType ().ToString ());
if (_headersWereSent) if (_headersSent)
throw new InvalidOperationException ("Cannot be changed after the headers are sent."); throw new InvalidOperationException ("Cannot be changed after the headers are sent.");
} }
@ -508,7 +505,7 @@ namespace WebSocketSharp.Net
#region Internal Methods #region Internal Methods
internal void SendHeaders (MemoryStream stream, bool closing) internal void WriteHeadersTo (MemoryStream destination, bool closing)
{ {
if (_contentType != null) { if (_contentType != null) {
var type = _contentType.IndexOf ("charset=", StringComparison.Ordinal) == -1 && var type = _contentType.IndexOf ("charset=", StringComparison.Ordinal) == -1 &&
@ -527,18 +524,19 @@ namespace WebSocketSharp.Net
_headers.InternalSet ("Date", DateTime.UtcNow.ToString ("r", prov), true); _headers.InternalSet ("Date", DateTime.UtcNow.ToString ("r", prov), true);
if (!_chunked) { if (!_chunked) {
if (!_contentLengthWasSet && closing) { if (!_contentLengthSet && closing) {
_contentLengthWasSet = true; _contentLengthSet = true;
_contentLength = 0; _contentLength = 0;
} }
if (_contentLengthWasSet) if (_contentLengthSet)
_headers.InternalSet ("Content-Length", _contentLength.ToString (prov), true); _headers.InternalSet ("Content-Length", _contentLength.ToString (prov), true);
else if (_context.Request.ProtocolVersion > HttpVersion.Version10)
_chunked = true;
} }
var ver = _context.Request.ProtocolVersion; if (_chunked)
if (!_contentLengthWasSet && !_chunked && ver > HttpVersion.Version10) _headers.InternalSet ("Transfer-Encoding", "chunked", true);
_chunked = true;
/* /*
* Apache forces closing the connection for these status codes: * Apache forces closing the connection for these status codes:
@ -556,34 +554,19 @@ namespace WebSocketSharp.Net
_statusCode == 413 || _statusCode == 413 ||
_statusCode == 414 || _statusCode == 414 ||
_statusCode == 500 || _statusCode == 500 ||
_statusCode == 503; _statusCode == 503 ||
!_context.Request.KeepAlive ||
if (!closeConn) !_keepAlive;
closeConn = !_context.Request.KeepAlive;
// They sent both KeepAlive: true and Connection: close!?
if (!_keepAlive || closeConn) {
_headers.InternalSet ("Connection", "close", true);
closeConn = true;
}
if (_chunked)
_headers.InternalSet ("Transfer-Encoding", "chunked", true);
var reuses = _context.Connection.Reuses; var reuses = _context.Connection.Reuses;
if (reuses >= 100) { if (closeConn || reuses >= 100) {
_forceCloseChunked = true; _headers.InternalSet ("Connection", "close", true);
if (!closeConn) {
_headers.InternalSet ("Connection", "close", true);
closeConn = true;
}
} }
else {
if (!closeConn) {
_headers.InternalSet ( _headers.InternalSet (
"Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses), true); "Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses), true);
if (ver < HttpVersion.Version11) if (_context.Request.ProtocolVersion < HttpVersion.Version11)
_headers.InternalSet ("Connection", "keep-alive", true); _headers.InternalSet ("Connection", "keep-alive", true);
} }
@ -595,18 +578,13 @@ namespace WebSocketSharp.Net
_headers.InternalSet ("Set-Cookie", cookie.ToResponseString (), true); _headers.InternalSet ("Set-Cookie", cookie.ToResponseString (), true);
var enc = _contentEncoding ?? Encoding.Default; var enc = _contentEncoding ?? Encoding.Default;
var writer = new StreamWriter (stream, enc, 256); var writer = new StreamWriter (destination, enc, 256);
writer.Write ("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription); writer.Write ("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription);
writer.Write (_headers.ToStringMultiValue (true)); writer.Write (_headers.ToStringMultiValue (true));
writer.Flush (); writer.Flush ();
// Assumes that the stream was at position 0. // Assumes that the destination was at position 0.
stream.Position = enc.CodePage == 65001 ? 3 : enc.GetPreamble ().Length; destination.Position = enc.CodePage == 65001 ? 3 : enc.GetPreamble ().Length;
if (_outputStream == null)
_outputStream = _context.Connection.GetResponseStream ();
_headersWereSent = true;
} }
#endregion #endregion
@ -625,8 +603,8 @@ namespace WebSocketSharp.Net
} }
/// <summary> /// <summary>
/// Adds an HTTP header with the specified <paramref name="name"/> and <paramref name="value"/> /// Adds an HTTP header with the specified <paramref name="name"/> and
/// to the headers for the response. /// <paramref name="value"/> to the headers for the response.
/// </summary> /// </summary>
/// <param name="name"> /// <param name="name">
/// A <see cref="string"/> that represents the name of the header to add. /// A <see cref="string"/> that represents the name of the header to add.

View File

@ -129,11 +129,13 @@ namespace WebSocketSharp.Net
{ {
if (!_response.HeadersSent) { if (!_response.HeadersSent) {
using (var headers = new MemoryStream ()) { using (var headers = new MemoryStream ()) {
_response.SendHeaders (headers, closing); _response.WriteHeadersTo (headers, closing);
var start = headers.Position; var start = headers.Position;
_write (headers.GetBuffer (), (int) start, (int) (headers.Length - start)); _write (headers.GetBuffer (), (int) start, (int) (headers.Length - start));
} }
_response.HeadersSent = true;
_chunked = _response.SendChunked; _chunked = _response.SendChunked;
_writeBody = _chunked ? _writeChunked : _write; _writeBody = _chunked ? _writeChunked : _write;
} }