How to send the 'Connection' header using HttpListenerResponse
Web Development
1
Posts
1
Posters
0
Views
1
Watching
-
Hello all.
While trying to implement a web-socket handshake, I encountered a weird behavior. It looks like the
HttpListenerResponse
class doesn't send the 'Connection' header.Here is an example for explaining what I mean:
public void TestWebSocketHttpHandshake()
{
int port = 9444;
ManualResetEvent serverStartedEvent = new ManualResetEvent(false);
ManualResetEvent clientClosedEvent = new ManualResetEvent(false);// HTTP server that gets a web-socket handshake request and, // send back a web-socket handshake response. async Task RunHttpServer() { HttpListener hl = new HttpListener(); hl.Prefixes.Add($"http://+:{port}/"); hl.Start(); serverStartedEvent.Set(); HttpListenerContext hlc = await hl.GetContextAsync(); string secWebSocketKeyHeader = hlc.Request.Headers\["Sec-WebSocket-Key"\]?.Trim(); string secWebSocketAcceptHeader = Convert.ToBase64String( System.Security.Cryptography.SHA1.Create().ComputeHash( Encoding.UTF8.GetBytes(secWebSocketKeyHeader + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") ) ); hlc.Response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // 101 hlc.Response.StatusDescription = "Switching Protocols"; hlc.Response.ProtocolVersion = new Version("1.1"); hlc.Response.AddHeader("Upgrade", "websocket"); **hlc.Response.AddHeader("Connection", "Upgrade");** hlc.Response.AddHeader("Sec-WebSocket-Accept", secWebSocketAcceptHeader); hlc.Response.Close(); // Wait for the client to close. clientClosedEvent.WaitOne(); hl.Stop(); } // Tcp Client that sends a web-socket handshake request and, // writes the received web-socket handshake response. async Task RunTcpClient() { const string eol = "\\r\\n"; // HTTP/1.1 defines the sequence CR LF as the end-of-line marker // Wait for the server to start. serverStartedEvent.WaitOne(); using (TcpClient tc = new TcpClient()) { tc.Connect("localhost", port); using (NetworkStream ns = tc.GetStream()) { string wsRequest = $"GET /chat HTTP/1.1{eol}Host: localhost:{port}{eol}"+ $"Upgrad