HttpListener from .NET 4.5 doesn't recognize socket as WebSocket

2.9k views Asked by At

From the .NET 4.5 FW there is builtin support for WebSockets handling.

http://msdn.microsoft.com/en-us/library/system.net.websockets.websocket(v=vs.110).aspx

The definition for creating WebSocket() instance in JS is simple as a crystal. Also... the way to handle WebSocket request in C# using .NET 4.5 is also simple... So I don't understand why in server-side code the incoming packet doesn't correspond to:

listenerContext.Request.IsWebSocketRequest

And it responses the 400 code (in else block).

My client code:

<script>
    function connect() {
        var ws = new WebSocket("ws://localhost:80/wsDemo/");
        ws.onopen = function () {
            alert("About to send data");
            ws.send("Hello World");
            alert("Message sent!");
        };

        ws.onmessage = function (evt) {
            alert("About to receive data");
            var received_msg = evt.data;
            alert("Message received = "+received_msg);
        };
        ws.onclose = function () { alert("Connection is closed..."); };
    };

    window.load = connect;

</script>

Server-side code:

    public async void Start(string listenerPrefix)
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add(listenerPrefix);
        listener.Start();
        Console.WriteLine("Listening...");

        while (true)
        {
            HttpListenerContext listenerContext = await listener.GetContextAsync();
            if (listenerContext.Request.IsWebSocketRequest)
            {
                ProcessRequest(listenerContext);
            }
            else
            {
                listenerContext.Response.StatusCode = 400;
                listenerContext.Response.Close();
            }
        }
    }
1

There are 1 answers

1
Levi On BEST ANSWER

What OS and browser are you running? Accepting WebSocket requests requires Windows 8 (or Server 2012) or later.