简体   繁体   中英

C# HttpListener Prefixes not accepting `ws` preventing JS WebSocket to connect

Scenario

  • C# Based Server
  • JavaScript Based Client

Situation

I created this fairly simple "server" which only job is to help me understanding how to actually use those websockets in a C# environment.

using (var server = new HttpListener())
{
    server.Prefixes.Add("http://localhost:8080/");
    server.Start();
    while(true)
    {
        var context = server.GetContext();
        if (context.Request.IsWebSocketRequest)
        {
            var cntxt = context.AcceptWebSocketAsync(null).ConfigureAwait(true).GetAwaiter().GetResult();
            var buff = new byte[2048];
            while(cntxt.WebSocket.State == System.Net.WebSockets.WebSocketState.Open || cntxt.WebSocket.State == System.Net.WebSockets.WebSocketState.Connecting)
            {
                cntxt.WebSocket.ReceiveAsync(new ArraySegment<byte>(buff), CancellationToken.None).ConfigureAwait(true).GetAwaiter().GetResult();
                Console.WriteLine(Encoding.UTF8.GetString(buff));
            }
        }
        else
        {
            context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            using (var writer = new StreamWriter(context.Response.OutputStream))
            {
                writer.Write("<html><body>WEBSOCKET ONLY!</body></html>");
            }
        }
    }
}

The problem now is: when i try to add the websocket prefix via server.Prefixes.Add("ws://localhost:8080") , i get some System.ArgumentException thrown which tells my i can only add http and https as accepted protocol.

Thing is: doing it and using ws = new WebSocket('ws://localhost:8080'); (JavaScript) to connect to a websocket, yields for obvious reasons nothing. Changing the prefix to HTTP in the JS websocket, will provide me with yet another sort-off argument exception.

Actual Question

how to actually get the HttpListener to acceppt web socket requests?

Further Info

Used .net framework is 4.6.1 Browser to test this was Google Chrome 69.0.3497.100

The reason for why the above was not working ... is due to the JS websocket requiring a path.

Changing the above HttpListener prefix to eg. "http://localhost:8080/asdasd/" will allow the socket to connect propertly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM