Renamed Handshake.cs to HandshakeBase.cs

This commit is contained in:
sta 2013-08-03 14:56:00 +09:00
parent 68d1a7b9ba
commit 3b009b852d
5 changed files with 159 additions and 162 deletions

View File

@ -1,6 +1,6 @@
#region License
/*
* Handshake.cs
* HandshakeBase.cs
*
* The MIT License
*
@ -31,10 +31,10 @@ using System.Collections.Specialized;
using System.Text;
using WebSocketSharp.Net;
namespace WebSocketSharp {
internal abstract class Handshake {
namespace WebSocketSharp
{
internal abstract class HandshakeBase
{
#region Protected Const Fields
protected const string CrLf = "\r\n";
@ -43,10 +43,10 @@ namespace WebSocketSharp {
#region Protected Constructors
protected Handshake()
protected HandshakeBase ()
{
ProtocolVersion = HttpVersion.Version11;
Headers = new NameValueCollection();
Headers = new NameValueCollection ();
}
#endregion
@ -65,29 +65,29 @@ namespace WebSocketSharp {
#region Public Methods
public void AddHeader(string name, string value)
public void AddHeader (string name, string value)
{
Headers.Add(name, value);
Headers.Add (name, value);
}
public bool ContainsHeader(string name)
public bool ContainsHeader (string name)
{
return Headers.Contains(name);
return Headers.Contains (name);
}
public bool ContainsHeader(string name, string value)
public bool ContainsHeader (string name, string value)
{
return Headers.Contains(name, value);
return Headers.Contains (name, value);
}
public string[] GetHeaderValues(string name)
public string [] GetHeaderValues (string name)
{
return Headers.GetValues(name);
return Headers.GetValues (name);
}
public byte[] ToByteArray()
public byte [] ToByteArray ()
{
return Encoding.UTF8.GetBytes(ToString());
return Encoding.UTF8.GetBytes (ToString ());
}
#endregion

View File

@ -33,9 +33,9 @@ using System.Text;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp {
internal class RequestHandshake : Handshake
namespace WebSocketSharp
{
internal class RequestHandshake : HandshakeBase
{
#region Private Fields
@ -45,7 +45,7 @@ namespace WebSocketSharp {
#region Private Constructors
private RequestHandshake()
private RequestHandshake ()
{
}
@ -53,13 +53,13 @@ namespace WebSocketSharp {
#region Public Constructors
public RequestHandshake(string uriString)
public RequestHandshake (string uriString)
{
HttpMethod = "GET";
RequestUri = uriString.ToUri();
AddHeader("User-Agent", "websocket-sharp/1.0");
AddHeader("Upgrade", "websocket");
AddHeader("Connection", "Upgrade");
RequestUri = uriString.ToUri ();
AddHeader ("User-Agent", "websocket-sharp/1.0");
AddHeader ("Upgrade", "websocket");
AddHeader ("Connection", "Upgrade");
}
#endregion
@ -68,7 +68,7 @@ namespace WebSocketSharp {
public CookieCollection Cookies {
get {
return Headers.GetCookies(false);
return Headers.GetCookies (false);
}
}
@ -82,15 +82,15 @@ namespace WebSocketSharp {
? false
: ProtocolVersion < HttpVersion.Version11
? false
: !ContainsHeader("Upgrade", "websocket")
: !ContainsHeader ("Upgrade", "websocket")
? false
: !ContainsHeader("Connection", "Upgrade")
: !ContainsHeader ("Connection", "Upgrade")
? false
: !ContainsHeader("Host")
: !ContainsHeader ("Host")
? false
: !ContainsHeader("Sec-WebSocket-Key")
: !ContainsHeader ("Sec-WebSocket-Key")
? false
: ContainsHeader("Sec-WebSocket-Version");
: ContainsHeader ("Sec-WebSocket-Version");
}
}
@ -98,21 +98,20 @@ namespace WebSocketSharp {
get {
if (_queryString == null)
{
_queryString = new NameValueCollection();
var i = RawUrl.IndexOf('?');
_queryString = new NameValueCollection ();
var i = RawUrl.IndexOf ('?');
if (i > 0)
{
var query = RawUrl.Substring(i + 1);
var components = query.Split('&');
var query = RawUrl.Substring (i + 1);
var components = query.Split ('&');
foreach (var c in components)
{
var nv = c.GetNameAndValue("=");
var nv = c.GetNameAndValue ("=");
if (nv.Key != null)
{
var name = nv.Key.UrlDecode();
var val = nv.Value.UrlDecode();
_queryString.Add(name, val);
var name = nv.Key.UrlDecode ();
var val = nv.Value.UrlDecode ();
_queryString.Add (name, val);
}
}
}
@ -138,28 +137,28 @@ namespace WebSocketSharp {
#region Public Methods
public static RequestHandshake Parse(string[] request)
public static RequestHandshake Parse (string [] request)
{
var requestLine = request[0].Split(' ');
var requestLine = request [0].Split (' ');
if (requestLine.Length != 3)
{
var msg = "Invalid HTTP Request-Line: " + request[0];
throw new ArgumentException(msg, "request");
var msg = "Invalid HTTP Request-Line: " + request [0];
throw new ArgumentException (msg, "request");
}
var headers = new WebHeaderCollection();
var headers = new WebHeaderCollection ();
for (int i = 1; i < request.Length; i++)
headers.SetInternal(request[i], false);
headers.SetInternal (request [i], false);
return new RequestHandshake {
Headers = headers,
HttpMethod = requestLine[0],
RequestUri = requestLine[1].ToUri(),
ProtocolVersion = new Version(requestLine[2].Substring(5))
HttpMethod = requestLine [0],
RequestUri = requestLine [1].ToUri (),
ProtocolVersion = new Version (requestLine [2].Substring (5))
};
}
public static RequestHandshake Parse(WebSocketContext context)
public static RequestHandshake Parse (WebSocketContext context)
{
return new RequestHandshake {
Headers = context.Headers,
@ -169,35 +168,35 @@ namespace WebSocketSharp {
};
}
public void SetCookies(CookieCollection cookies)
public void SetCookies (CookieCollection cookies)
{
if (cookies == null || cookies.Count == 0)
return;
var sorted = cookies.Sorted.ToArray();
var header = new StringBuilder(sorted[0].ToString(), 64);
var sorted = cookies.Sorted.ToArray ();
var header = new StringBuilder (sorted [0].ToString (), 64);
for (int i = 1; i < sorted.Length; i++)
if (!sorted[i].Expired)
header.AppendFormat("; {0}", sorted[i].ToString());
if (!sorted [i].Expired)
header.AppendFormat ("; {0}", sorted [i].ToString ());
AddHeader("Cookie", header.ToString());
AddHeader ("Cookie", header.ToString ());
}
public void SetAuthorization(AuthenticationResponse response)
public void SetAuthorization (AuthenticationResponse response)
{
var credentials = response.ToString();
AddHeader("Authorization", credentials);
var credentials = response.ToString ();
AddHeader ("Authorization", credentials);
}
public override string ToString()
public override string ToString ()
{
var buffer = new StringBuilder(64);
buffer.AppendFormat("{0} {1} HTTP/{2}{3}", HttpMethod, RawUrl, ProtocolVersion, CrLf);
var buffer = new StringBuilder (64);
buffer.AppendFormat ("{0} {1} HTTP/{2}{3}", HttpMethod, RawUrl, ProtocolVersion, CrLf);
foreach (string key in Headers.AllKeys)
buffer.AppendFormat("{0}: {1}{2}", key, Headers[key], CrLf);
buffer.AppendFormat ("{0}: {1}{2}", key, Headers [key], CrLf);
buffer.Append(CrLf);
return buffer.ToString();
buffer.Append (CrLf);
return buffer.ToString ();
}
#endregion

View File

@ -31,24 +31,24 @@ using System.Collections.Specialized;
using System.Text;
using WebSocketSharp.Net;
namespace WebSocketSharp {
internal class ResponseHandshake : Handshake
namespace WebSocketSharp
{
internal class ResponseHandshake : HandshakeBase
{
#region Public Constructors
public ResponseHandshake()
: this(HttpStatusCode.SwitchingProtocols)
public ResponseHandshake ()
: this (HttpStatusCode.SwitchingProtocols)
{
AddHeader("Upgrade", "websocket");
AddHeader("Connection", "Upgrade");
AddHeader ("Upgrade", "websocket");
AddHeader ("Connection", "Upgrade");
}
public ResponseHandshake(HttpStatusCode code)
public ResponseHandshake (HttpStatusCode code)
{
StatusCode = ((int)code).ToString();
Reason = code.GetDescription();
AddHeader("Server", "websocket-sharp/1.0");
StatusCode = ((int) code).ToString ();
Reason = code.GetDescription ();
AddHeader ("Server", "websocket-sharp/1.0");
}
#endregion
@ -57,15 +57,15 @@ namespace WebSocketSharp {
public AuthenticationChallenge AuthChallenge {
get {
return ContainsHeader("WWW-Authenticate")
? AuthenticationChallenge.Parse(Headers["WWW-Authenticate"])
return ContainsHeader ("WWW-Authenticate")
? AuthenticationChallenge.Parse (Headers ["WWW-Authenticate"])
: null;
}
}
public CookieCollection Cookies {
get {
return Headers.GetCookies(true);
return Headers.GetCookies (true);
}
}
@ -81,11 +81,11 @@ namespace WebSocketSharp {
? false
: StatusCode != "101"
? false
: !ContainsHeader("Upgrade", "websocket")
: !ContainsHeader ("Upgrade", "websocket")
? false
: !ContainsHeader("Connection", "Upgrade")
: !ContainsHeader ("Connection", "Upgrade")
? false
: ContainsHeader("Sec-WebSocket-Accept");
: ContainsHeader ("Sec-WebSocket-Accept");
}
}
@ -101,54 +101,54 @@ namespace WebSocketSharp {
#region Public Methods
public static ResponseHandshake CreateCloseResponse(HttpStatusCode code)
public static ResponseHandshake CreateCloseResponse (HttpStatusCode code)
{
var res = new ResponseHandshake(code);
res.AddHeader("Connection", "close");
var res = new ResponseHandshake (code);
res.AddHeader ("Connection", "close");
return res;
}
public static ResponseHandshake Parse(string[] response)
public static ResponseHandshake Parse (string [] response)
{
var statusLine = response[0].Split(' ');
var statusLine = response [0].Split (' ');
if (statusLine.Length < 3)
throw new ArgumentException("Invalid status line.");
throw new ArgumentException ("Invalid status line.");
var reason = new StringBuilder(statusLine[2], 64);
var reason = new StringBuilder (statusLine [2], 64);
for (int i = 3; i < statusLine.Length; i++)
reason.AppendFormat(" {0}", statusLine[i]);
reason.AppendFormat (" {0}", statusLine [i]);
var headers = new WebHeaderCollection();
var headers = new WebHeaderCollection ();
for (int i = 1; i < response.Length; i++)
headers.SetInternal(response[i], true);
headers.SetInternal (response [i], true);
return new ResponseHandshake {
Headers = headers,
Reason = reason.ToString(),
StatusCode = statusLine[1],
ProtocolVersion = new Version(statusLine[0].Substring(5))
Reason = reason.ToString (),
StatusCode = statusLine [1],
ProtocolVersion = new Version (statusLine [0].Substring (5))
};
}
public void SetCookies(CookieCollection cookies)
public void SetCookies (CookieCollection cookies)
{
if (cookies == null || cookies.Count == 0)
return;
foreach (var cookie in cookies.Sorted)
AddHeader("Set-Cookie", cookie.ToResponseString());
AddHeader ("Set-Cookie", cookie.ToResponseString ());
}
public override string ToString()
public override string ToString ()
{
var buffer = new StringBuilder(64);
buffer.AppendFormat("HTTP/{0} {1} {2}{3}", ProtocolVersion, StatusCode, Reason, CrLf);
var buffer = new StringBuilder (64);
buffer.AppendFormat ("HTTP/{0} {1} {2}{3}", ProtocolVersion, StatusCode, Reason, CrLf);
foreach (string key in Headers.AllKeys)
buffer.AppendFormat("{0}: {1}{2}", key, Headers[key], CrLf);
buffer.AppendFormat ("{0}: {1}{2}", key, Headers [key], CrLf);
buffer.Append(CrLf);
return buffer.ToString();
buffer.Append (CrLf);
return buffer.ToString ();
}
#endregion

View File

@ -35,8 +35,8 @@ using System.Text;
using WebSocketSharp.Net;
using WebSocketSharp.Net.Security;
namespace WebSocketSharp {
namespace WebSocketSharp
{
internal class WsStream : IDisposable
{
#region Private Const Fields
@ -56,25 +56,25 @@ namespace WebSocketSharp {
#region Private Constructors
private WsStream(Stream innerStream, bool secure)
private WsStream (Stream innerStream, bool secure)
{
_innerStream = innerStream;
_secure = secure;
_forRead = new object();
_forWrite = new object();
_forRead = new object ();
_forWrite = new object ();
}
#endregion
#region Internal Constructors
internal WsStream(NetworkStream innerStream)
: this(innerStream, false)
internal WsStream (NetworkStream innerStream)
: this (innerStream, false)
{
}
internal WsStream(SslStream innerStream)
: this(innerStream, true)
internal WsStream (SslStream innerStream)
: this (innerStream, true)
{
}
@ -85,8 +85,8 @@ namespace WebSocketSharp {
public bool DataAvailable {
get {
return _secure
? ((SslStream)_innerStream).DataAvailable
: ((NetworkStream)_innerStream).DataAvailable;
? ((SslStream) _innerStream).DataAvailable
: ((NetworkStream) _innerStream).DataAvailable;
}
}
@ -100,12 +100,12 @@ namespace WebSocketSharp {
#region Private Methods
private bool write(byte[] data)
private bool write (byte [] data)
{
lock (_forWrite)
{
try {
_innerStream.Write(data, 0, data.Length);
_innerStream.Write (data, 0, data.Length);
return true;
}
catch {
@ -118,93 +118,91 @@ namespace WebSocketSharp {
#region Internal Methods
internal static WsStream CreateClientStream(
internal static WsStream CreateClientStream (
TcpClient client,
bool secure,
string host,
System.Net.Security.RemoteCertificateValidationCallback validationCallback
)
{
var netStream = client.GetStream();
var netStream = client.GetStream ();
if (secure)
{
if (validationCallback == null)
validationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
var sslStream = new SslStream(netStream, false, validationCallback);
sslStream.AuthenticateAsClient(host);
var sslStream = new SslStream (netStream, false, validationCallback);
sslStream.AuthenticateAsClient (host);
return new WsStream(sslStream);
return new WsStream (sslStream);
}
return new WsStream(netStream);
return new WsStream (netStream);
}
internal static WsStream CreateServerStream(TcpClient client, bool secure, X509Certificate cert)
internal static WsStream CreateServerStream (TcpClient client, bool secure, X509Certificate cert)
{
var netStream = client.GetStream();
var netStream = client.GetStream ();
if (secure)
{
var sslStream = new SslStream(netStream, false);
sslStream.AuthenticateAsServer(cert);
var sslStream = new SslStream (netStream, false);
sslStream.AuthenticateAsServer (cert);
return new WsStream(sslStream);
return new WsStream (sslStream);
}
return new WsStream(netStream);
return new WsStream (netStream);
}
internal static WsStream CreateServerStream(HttpListenerContext context)
internal static WsStream CreateServerStream (HttpListenerContext context)
{
var conn = context.Connection;
return new WsStream(conn.Stream, conn.IsSecure);
return new WsStream (conn.Stream, conn.IsSecure);
}
#endregion
#region Public Methods
public void Close()
public void Close ()
{
_innerStream.Close();
_innerStream.Close ();
}
public void Dispose()
public void Dispose ()
{
_innerStream.Dispose();
_innerStream.Dispose ();
}
public WsFrame ReadFrame()
public WsFrame ReadFrame ()
{
lock (_forRead)
{
try
{
return WsFrame.Parse(_innerStream);
try {
return WsFrame.Parse (_innerStream);
}
catch
{
catch {
return null;
}
}
}
public void ReadFrameAsync(Action<WsFrame> completed)
public void ReadFrameAsync (Action<WsFrame> completed)
{
WsFrame.ParseAsync(_innerStream, completed);
WsFrame.ParseAsync (_innerStream, completed);
}
public string[] ReadHandshake()
public string [] ReadHandshake ()
{
var read = false;
var buffer = new List<byte>();
Action<int> add = i => buffer.Add((byte)i);
var buffer = new List<byte> ();
Action<int> add = i => buffer.Add ((byte) i);
while (buffer.Count < _handshakeLimitLen)
{
if (_innerStream.ReadByte().EqualsWith('\r', add) &&
_innerStream.ReadByte().EqualsWith('\n', add) &&
_innerStream.ReadByte().EqualsWith('\r', add) &&
_innerStream.ReadByte().EqualsWith('\n', add))
if (_innerStream.ReadByte ().EqualsWith ('\r', add) &&
_innerStream.ReadByte ().EqualsWith ('\n', add) &&
_innerStream.ReadByte ().EqualsWith ('\r', add) &&
_innerStream.ReadByte ().EqualsWith ('\n', add))
{
read = true;
break;
@ -212,24 +210,24 @@ namespace WebSocketSharp {
}
if (!read)
throw new WebSocketException("The length of the handshake is greater than the limit length.");
throw new WebSocketException ("The length of the handshake is greater than the limit length.");
return Encoding.UTF8.GetString(buffer.ToArray())
.Replace("\r\n", "\n")
.Replace("\n ", " ")
.Replace("\n\t", " ")
.TrimEnd('\n')
.Split('\n');
return Encoding.UTF8.GetString (buffer.ToArray ())
.Replace ("\r\n", "\n")
.Replace ("\n ", " ")
.Replace ("\n\t", " ")
.TrimEnd ('\n')
.Split ('\n');
}
public bool WriteFrame(WsFrame frame)
public bool WriteFrame (WsFrame frame)
{
return write(frame.ToByteArray());
return write (frame.ToByteArray ());
}
public bool WriteHandshake(Handshake handshake)
public bool WriteHandshake (HandshakeBase handshake)
{
return write(handshake.ToByteArray());
return write (handshake.ToByteArray ());
}
#endregion

View File

@ -74,7 +74,6 @@
<Compile Include="WsStream.cs" />
<Compile Include="RequestHandshake.cs" />
<Compile Include="ResponseHandshake.cs" />
<Compile Include="Handshake.cs" />
<Compile Include="Net\AuthenticationSchemeSelector.cs" />
<Compile Include="Net\AuthenticationSchemes.cs" />
<Compile Include="Net\ChunkStream.cs" />
@ -128,6 +127,7 @@
<Compile Include="LogData.cs" />
<Compile Include="LogLevel.cs" />
<Compile Include="Logger.cs" />
<Compile Include="HandshakeBase.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>