private bool HandleUpgradeResponse() { Func <string> acceptkey = () => { using (SHA1 sha1 = SHA1.Create()) { StringBuilder ss = new StringBuilder(); string key = _secWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(key)); return(Convert.ToBase64String(hash)); } }; StringBuilder headers = new StringBuilder(); headers.Append("HTTP/1.1 101 Switching Protocols\r\n"); headers.Append("Upgrade: websocket\r\n"); headers.Append("Connection: Upgrade\r\n"); headers.AppendFormat("Sec-WebSocket-Accept: {0}\r\n", acceptkey()); headers.AppendFormat("Sec-WebSocket-Origin: {0}\r\n", _origin); headers.AppendFormat("Sec-WebSocket-Location: ws://{0}{1}\r\n\r\n", _host, _rawUri); byte[] response = Encoding.UTF8.GetBytes(headers.ToString()); lock (_signal) { if (!_socket.Connected || SocketExtension.CleanedUp(_socket)) { return(false); } return(SocketExtension.BeginSend(_socket, response, 0, response.Length, null)); } }
public bool Send(OpCode opcode, byte[] buffer) { if (buffer == null) { return(false); } lock (this) { if (!socket.Connected) { return(false); } WebSocketFrame frame = new WebSocketFrame(); frame.opcode = (byte)opcode; frame.fin = true; frame.rsv1 = false; frame.rsv2 = false; frame.rsv3 = false; frame.masked = clientMode; // 客户端需要加密;服务器禁止加密(chrome) frame.payload_data = buffer; frame.payload_length = buffer.Length; using (MemoryStream s = WebSocketFrame.Pack(frame)) { return(SocketExtension.BeginSend(socket, s.GetBuffer(), 0, (int)s.Position, null)); } } }
private bool SendUpgradeRequest() { lock (_signal) { if (!_socket.Connected || SocketExtension.CleanedUp(_socket)) { return(false); } } StringBuilder sb = new StringBuilder(); sb.AppendFormat("GET {0} HTTP/1.1\r\n", _uri.AbsolutePath); sb.AppendFormat("Host: {0}:{1}\r\n", _uri.Host, _uri.Port); sb.Append("Connection: Upgrade\r\n"); sb.Append("Pragma: no-cache\r\n"); sb.Append("Cache-Control: no-cache\r\n"); sb.Append("Upgrade: websocket\r\n"); sb.Append("Origin: null\r\n"); sb.Append("Accept-Encoding: gzip, deflate, br\r\n"); sb.Append("Accept-Language: zh-CN,zh;q=0.9\r\n"); sb.Append("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36\r\n"); sb.AppendFormat("Sec-WebSocket-Key: {0}\r\n", _secWebSocketKey); sb.Append("Sec-WebSocket-Origin: null\r\n"); sb.Append("Sec-WebSocket-Version: 13\r\n"); sb.Append("Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits\r\n\r\n"); byte[] request = Encoding.UTF8.GetBytes(sb.ToString()); if (!SocketExtension.BeginSend(_socket, request, 0, request.Length, null)) { return(false); } return(true); }