Saturday, November 26, 2011

Websocket asp.net fx4.5


(1) Need to turn on IIS features, Fx 4.5 and WebScoket from Control Panel
(2) Currently must run ASP.Net project in IIS 8.0. So project config must uncheck IIS express. May also need to clean up applicationHost.Config to clear all site/project pointing to port 80.

Make a httpHandler

public void ProcessRequest(HttpContext ctx)
{

if (ctx.IsWebSocketRequest)
{
Microsoft.Web.WebSockets.WebSocketExtensions.AcceptWebSocketRequest(ctx, new Class1());
// ctx.AcceptWebSocketRequest(Test);
}
else
{
ctx.Response.StatusCode = 400;
}
}

async Task Test(AspNetWebSocketContext wsCtx)
{
AspNetWebSocket ws = wsCtx.WebSocket as AspNetWebSocket;
string UserMsg = "Test from WS";
WebSocketHandler wsH = new WebSocketHandler();
wsH.WebSocketContext = wsCtx;
ArraySegment arrS = new ArraySegment(Encoding.UTF8.GetBytes(UserMsg));
wsH.Send(UserMsg);
await ws.SendAsync(arrS, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
}

public class Class1: WebSocketHandler
{
}
Use JQuery to connect
<
script src="Scripts/jquery-1.7.1.js" ></script>
<script>
$(function () {
$("#b").click(function () {

var conn = new WebSocket("ws://localhost/TestWebSocket2/test.ashx");

conn.onmessage = function (msg) {
alert(msg.data);
}
});
});
</script>

</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<input type="button" value="Connect to WS" id="b" />

Both JQuery and WebSocket can be downloaded from NuGet