This simple web socket example returns error 200.
Edit: I am retelling the code in C # in the hope that more people will be able to advise me why I have such a problem.
I run VS2012 Express, on my local IIS machine the project is configured for framework 4.5.1, and I imported the Microsoft.Websockets Nuget package.
The three code snippets that I included below are only three pieces of code in the project, and I did not make any changes to the rest of the project.
There is no gap before an unexpected error; it does not interrupt when opening or in a message from both sides. 200 appears as an error in the chrome console, but there is no preview of the response.
Here is the client (index.htm):
<!doctype html> <html> <head> <title></title> <script src="Scripts/jquery-1.8.1.js" type="text/javascript"></script> <script src="test.js" type="text/javascript"></script> </head> <body> <input id="txtMessage" /> <input id="cmdSend" type="button" value="Send" /> <input id="cmdLeave" type="button" value="Leave" /> <br /> <div id="chatMessages" /> </body> </html>
and client script (test.js):
$(document).ready(function () { var name = prompt('what is your name?:'); var url = 'ws://' + window.location.hostname + window.location.pathname.replace('index.htm', 'ws.ashx') + '?name=' + name; alert('Connecting to: ' + url); var ws = new WebSocket(url); ws.onopen = function () { $('#messages').prepend('Connected <br/>'); $('#cmdSend').click(function () { ws.send($('#txtMessage').val()); $('#txtMessage').val(''); }); }; ws.onmessage = function (e) { $('#chatMessages').prepend(e.data + '<br/>'); }; $('#cmdLeave').click(function () { ws.close(); }); ws.onclose = function () { $('#chatMessages').prepend('Closed <br/>'); }; ws.onerror = function (e) { $('#chatMessages').prepend('Oops something went wrong<br/>'); }; });
Here is the generic handler (ws.ashx):
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.Web.WebSockets; namespace WebSockets { public class ws : IHttpHandler { public void ProcessRequest(HttpContext context) { if (context.IsWebSocketRequest) context.AcceptWebSocketRequest(new TestWebSocketHandler()); } public bool IsReusable { get { return false; } } } }
Here is the class (TestWebSocketHandler):
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using Microsoft.Web.WebSockets; namespace WebSockets { public class TestWebSocketHandler : WebSocketHandler { private static WebSocketCollection clients = new WebSocketCollection(); private string name; public override void OnOpen() { this.name = this.WebSocketContext.QueryString["name"]; clients.Add(this); clients.Broadcast(name + " has connected."); } public override void OnMessage(string message) { clients.Broadcast(string.Format("{0} said: {1}", name, message)); } public override void OnClose() { clients.Remove(this); clients.Broadcast(string.Format("{0} has gone away.", name)); } } }