public Task<WebSocketConnection> Hanshake(NetworkStream stream, Uri uri, string protocol, string origin) { var result = new Task<WebSocketConnection>(() => { var keyBytes = new byte[16]; var random = new Random(); random.NextBytes(keyBytes); var key = Convert.ToBase64String(keyBytes); var requestSb = new StringBuilder(); requestSb.AppendFormat("GET {0} HTTP/1.1\n", uri.PathAndQuery); requestSb.AppendFormat("Host: {0}\n", uri.Host); requestSb.AppendLine("Upgrade: websocket"); requestSb.AppendLine("Connection: Upgrade"); requestSb.AppendFormat("Sec-WebSocket-Key: {0}\n", key); if (!String.IsNullOrEmpty(origin)) requestSb.AppendFormat("Origin: {0}\n", origin); if (!String.IsNullOrEmpty(protocol)) requestSb.AppendFormat("Sec-WebSocket-Protocol: {0}\n", protocol); requestSb.AppendLine("Sec-WebSocket-Version: 13"); requestSb.AppendLine(); var request = requestSb.ToString(); var reader = new StreamReader(stream); var writer = new StreamWriter(stream); writer.Write(request); writer.Flush(); var responseLines = new List<string>(); try { string str; while (!String.IsNullOrEmpty(str = reader.ReadLine())) { responseLines.Add(str); } } catch (IOException) { return null; } var message = new HttpResponse(responseLines); if (message.ResponseCode != "101") return null; var response = message.Headers["Sec-WebSocket-Accept"]; var expectedResponse = WebSocketHandshaker.GetSecWebSocketKeyResponse(key); if (response != expectedResponse) return null; var connection = new WebSocketConnection(stream); connection.StartRead(); return connection; }); result.Start(); return result; }
public WebSocketConnectionEventArgs(WebSocketConnection connection, NetworkStream stream, string uri, string origin, IEnumerable<string> protocols, IDictionary<string, string> headers) { Connection = connection; Stream = stream; Uri = uri; Origin = origin; Protocols = protocols; Headers = headers; }
private WebSocketConnection CreateNewConnection(NetworkStream stream) { var connection = new WebSocketConnection(stream); lock (_connections) { _connections.Add(connection); } connection.Closed += ConnectionClosedHandler; connection.StartRead(); return connection; }
public WebSocketConnectionEventArgs(WebSocketConnection connection, NetworkStream stream) : this(connection, stream, null, null, null, null) { }