Renamed HandshakeRequest.cs to HttpRequest.cs, and refactored

This commit is contained in:
sta 2014-07-14 20:34:43 +09:00
parent f75b8fde86
commit 4427838632
5 changed files with 58 additions and 48 deletions

View File

@ -1,6 +1,6 @@
#region License #region License
/* /*
* HandshakeRequest.cs * HttpRequest.cs
* *
* The MIT License * The MIT License
* *
@ -33,7 +33,7 @@ using WebSocketSharp.Net;
namespace WebSocketSharp namespace WebSocketSharp
{ {
internal class HandshakeRequest : HttpBase internal class HttpRequest : HttpBase
{ {
#region Private Fields #region Private Fields
@ -46,25 +46,21 @@ namespace WebSocketSharp
#region Private Constructors #region Private Constructors
private HandshakeRequest (Version version, NameValueCollection headers) private HttpRequest (string method, string uri, Version version, NameValueCollection headers)
: base (version, headers) : base (version, headers)
{ {
_method = method;
_uri = uri;
} }
#endregion #endregion
#region Internal Constructors #region Internal Constructors
internal HandshakeRequest (string pathAndQuery) internal HttpRequest (string method, string uri)
: base (HttpVersion.Version11, new NameValueCollection ()) : this (method, uri, HttpVersion.Version11, new NameValueCollection ())
{ {
_uri = pathAndQuery; Headers["User-Agent"] = "websocket-sharp/1.0";
_method = "GET";
var headers = Headers;
headers["User-Agent"] = "websocket-sharp/1.0";
headers["Upgrade"] = "websocket";
headers["Connection"] = "Upgrade";
} }
#endregion #endregion
@ -118,7 +114,28 @@ namespace WebSocketSharp
#region Internal Methods #region Internal Methods
internal static HandshakeRequest Parse (string[] headerParts) internal static HttpRequest CreateConnectRequest (Uri uri)
{
var authority = uri.Authority;
var req = new HttpRequest ("CONNECT", authority);
req.Headers["Host"] = uri.Port == 80 ? uri.DnsSafeHost : authority;
return req;
}
internal static HttpRequest CreateWebSocketRequest (Uri uri)
{
var req = new HttpRequest ("GET", uri.PathAndQuery);
var headers = req.Headers;
headers["Upgrade"] = "websocket";
headers["Connection"] = "Upgrade";
headers["Host"] = uri.Port == 80 ? uri.DnsSafeHost : uri.Authority;
return req;
}
internal static HttpRequest Parse (string[] headerParts)
{ {
var requestLine = headerParts[0].Split (new[] { ' ' }, 3); var requestLine = headerParts[0].Split (new[] { ' ' }, 3);
if (requestLine.Length != 3) if (requestLine.Length != 3)
@ -128,11 +145,8 @@ namespace WebSocketSharp
for (int i = 1; i < headerParts.Length; i++) for (int i = 1; i < headerParts.Length; i++)
headers.SetInternally (headerParts[i], false); headers.SetInternally (headerParts[i], false);
var req = new HandshakeRequest (new Version (requestLine[2].Substring (5)), headers); return new HttpRequest (
req._method = requestLine[0]; requestLine[0], requestLine[1], new Version (requestLine[2].Substring (5)), headers);
req._uri = requestLine[1];
return req;
} }
#endregion #endregion

View File

@ -49,7 +49,7 @@ namespace WebSocketSharp.Net.WebSockets
private TcpClient _client; private TcpClient _client;
private CookieCollection _cookies; private CookieCollection _cookies;
private NameValueCollection _queryString; private NameValueCollection _queryString;
private HandshakeRequest _request; private HttpRequest _request;
private bool _secure; private bool _secure;
private WebSocketStream _stream; private WebSocketStream _stream;
private Uri _uri; private Uri _uri;
@ -66,7 +66,7 @@ namespace WebSocketSharp.Net.WebSockets
_client = client; _client = client;
_secure = secure; _secure = secure;
_stream = WebSocketStream.CreateServerStream (client, secure, cert); _stream = WebSocketStream.CreateServerStream (client, secure, cert);
_request = _stream.ReadHandshake<HandshakeRequest> (HandshakeRequest.Parse, 90000); _request = _stream.ReadHttp<HttpRequest> (HttpRequest.Parse, 90000);
_uri = HttpUtility.CreateRequestUrl ( _uri = HttpUtility.CreateRequestUrl (
_request.RequestUri, _request.Headers ["Host"], _request.IsWebSocketRequest, secure); _request.RequestUri, _request.Headers ["Host"], _request.IsWebSocketRequest, secure);
@ -329,7 +329,7 @@ namespace WebSocketSharp.Net.WebSockets
var res = new HandshakeResponse (HttpStatusCode.Unauthorized); var res = new HandshakeResponse (HttpStatusCode.Unauthorized);
res.Headers ["WWW-Authenticate"] = challenge; res.Headers ["WWW-Authenticate"] = challenge;
_stream.WriteHandshake (res); _stream.WriteHandshake (res);
_request = _stream.ReadHandshake<HandshakeRequest> (HandshakeRequest.Parse, 15000); _request = _stream.ReadHttp<HttpRequest> (HttpRequest.Parse, 15000);
} }
internal void SetUser ( internal void SetUser (

View File

@ -898,16 +898,11 @@ namespace WebSocketSharp
} }
// As client // As client
private HandshakeRequest createHandshakeRequest () private HttpRequest createHandshakeRequest ()
{ {
var path = _uri.PathAndQuery; var req = HttpRequest.CreateWebSocketRequest (_uri);
var host = _uri.Port == 80 ? _uri.DnsSafeHost : _uri.Authority;
var req = new HandshakeRequest (path);
var headers = req.Headers; var headers = req.Headers;
headers ["Host"] = host;
if (!_origin.IsNullOrEmpty ()) if (!_origin.IsNullOrEmpty ())
headers ["Origin"] = _origin; headers ["Origin"] = _origin;
@ -927,8 +922,9 @@ namespace WebSocketSharp
authRes = new AuthenticationResponse (_authChallenge, _credentials, _nonceCount); authRes = new AuthenticationResponse (_authChallenge, _credentials, _nonceCount);
_nonceCount = authRes.NonceCount; _nonceCount = authRes.NonceCount;
} }
else if (_preAuth) else if (_preAuth) {
authRes = new AuthenticationResponse (_credentials); authRes = new AuthenticationResponse (_credentials);
}
if (authRes != null) if (authRes != null)
headers ["Authorization"] = authRes.ToString (); headers ["Authorization"] = authRes.ToString ();
@ -1068,7 +1064,7 @@ namespace WebSocketSharp
} }
// As client // As client
private void send (HandshakeRequest request) private void send (HttpRequest request)
{ {
_logger.Debug ( _logger.Debug (
String.Format ("A WebSocket connection request to {0}:\n{1}", _uri, request)); String.Format ("A WebSocket connection request to {0}:\n{1}", _uri, request));
@ -1254,7 +1250,7 @@ namespace WebSocketSharp
} }
// As client // As client
private HandshakeResponse sendHandshakeRequest (HandshakeRequest request) private HandshakeResponse sendHandshakeRequest (HttpRequest request)
{ {
send (request); send (request);
return receiveHandshakeResponse (); return receiveHandshakeResponse ();

View File

@ -42,7 +42,7 @@ namespace WebSocketSharp
{ {
#region Private Const Fields #region Private Const Fields
private const int _handshakeHeadersLimitLen = 8192; private const int _httpHeadersLimitLen = 8192;
#endregion #endregion
@ -99,7 +99,7 @@ namespace WebSocketSharp
#region Private Methods #region Private Methods
private static byte [] readHandshakeEntityBody (Stream stream, string length) private static byte [] readHttpEntityBody (Stream stream, string length)
{ {
long len; long len;
if (!Int64.TryParse (length, out len)) if (!Int64.TryParse (length, out len))
@ -115,7 +115,7 @@ namespace WebSocketSharp
: null; : null;
} }
private static string [] readHandshakeHeaders (Stream stream) private static string [] readHttpHeaders (Stream stream)
{ {
var buff = new List<byte> (); var buff = new List<byte> ();
var count = 0; var count = 0;
@ -125,7 +125,7 @@ namespace WebSocketSharp
}; };
var read = false; var read = false;
while (count < _handshakeHeadersLimitLen) { while (count < _httpHeadersLimitLen) {
if (stream.ReadByte ().EqualsWith ('\r', add) && if (stream.ReadByte ().EqualsWith ('\r', add) &&
stream.ReadByte ().EqualsWith ('\n', add) && stream.ReadByte ().EqualsWith ('\n', add) &&
stream.ReadByte ().EqualsWith ('\r', add) && stream.ReadByte ().EqualsWith ('\r', add) &&
@ -137,7 +137,7 @@ namespace WebSocketSharp
if (!read) if (!read)
throw new WebSocketException ( throw new WebSocketException (
"The header part of a handshake is greater than the limit length."); "The header part of a HTTP data is greater than the limit length.");
var crlf = "\r\n"; var crlf = "\r\n";
return Encoding.UTF8.GetString (buff.ToArray ()) return Encoding.UTF8.GetString (buff.ToArray ())
@ -150,7 +150,7 @@ namespace WebSocketSharp
#region Internal Methods #region Internal Methods
internal T ReadHandshake<T> (Func<string [], T> parser, int millisecondsTimeout) internal T ReadHttp<T> (Func<string [], T> parser, int millisecondsTimeout)
where T : HttpBase where T : HttpBase
{ {
var timeout = false; var timeout = false;
@ -163,13 +163,13 @@ namespace WebSocketSharp
millisecondsTimeout, millisecondsTimeout,
-1); -1);
T handshake = null; T http = null;
Exception exception = null; Exception exception = null;
try { try {
handshake = parser (readHandshakeHeaders (_innerStream)); http = parser (readHttpHeaders (_innerStream));
var contentLen = handshake.Headers ["Content-Length"]; var contentLen = http.Headers ["Content-Length"];
if (contentLen != null && contentLen.Length > 0) if (contentLen != null && contentLen.Length > 0)
handshake.EntityBodyData = readHandshakeEntityBody (_innerStream, contentLen); http.EntityBodyData = readHttpEntityBody (_innerStream, contentLen);
} }
catch (Exception ex) { catch (Exception ex) {
exception = ex; exception = ex;
@ -180,15 +180,15 @@ namespace WebSocketSharp
} }
var msg = timeout var msg = timeout
? "A timeout has occurred while receiving a handshake." ? "A timeout has occurred while receiving a HTTP data."
: exception != null : exception != null
? "An exception has occurred while receiving a handshake." ? "An exception has occurred while receiving a HTTP data."
: null; : null;
if (msg != null) if (msg != null)
throw new WebSocketException (msg, exception); throw new WebSocketException (msg, exception);
return handshake; return http;
} }
internal bool Write (byte [] data) internal bool Write (byte [] data)
@ -262,14 +262,14 @@ namespace WebSocketSharp
WebSocketFrame.ParseAsync (_innerStream, true, completed, error); WebSocketFrame.ParseAsync (_innerStream, true, completed, error);
} }
public HandshakeRequest ReadHandshakeRequest () public HttpRequest ReadHandshakeRequest ()
{ {
return ReadHandshake<HandshakeRequest> (HandshakeRequest.Parse, 90000); return ReadHttp<HttpRequest> (HttpRequest.Parse, 90000);
} }
public HandshakeResponse ReadHandshakeResponse () public HandshakeResponse ReadHandshakeResponse ()
{ {
return ReadHandshake<HandshakeResponse> (HandshakeResponse.Parse, 90000); return ReadHttp<HandshakeResponse> (HandshakeResponse.Parse, 90000);
} }
public bool WriteFrame (WebSocketFrame frame) public bool WriteFrame (WebSocketFrame frame)

View File

@ -113,7 +113,6 @@
<Compile Include="LogData.cs" /> <Compile Include="LogData.cs" />
<Compile Include="LogLevel.cs" /> <Compile Include="LogLevel.cs" />
<Compile Include="Logger.cs" /> <Compile Include="Logger.cs" />
<Compile Include="HandshakeRequest.cs" />
<Compile Include="HandshakeResponse.cs" /> <Compile Include="HandshakeResponse.cs" />
<Compile Include="WebSocketState.cs" /> <Compile Include="WebSocketState.cs" />
<Compile Include="Server\IWebSocketSession.cs" /> <Compile Include="Server\IWebSocketSession.cs" />
@ -136,6 +135,7 @@
<Compile Include="Net\AuthenticationResponse.cs" /> <Compile Include="Net\AuthenticationResponse.cs" />
<Compile Include="Net\AuthenticationBase.cs" /> <Compile Include="Net\AuthenticationBase.cs" />
<Compile Include="HttpBase.cs" /> <Compile Include="HttpBase.cs" />
<Compile Include="HttpRequest.cs" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup> <ItemGroup>