Separate Open and Message and use Collection to Broadcast
public class JsonWebSocketHandler : WebSocketHandler
{
WebSocketCollection _wsCns = new WebSocketCollection();
public override void OnMessage(string message)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
_wsCns.Broadcast(ser.Serialize( new
{
data="Test",
id=1
}));
}
public override void OnOpen()
{
_wsCns.Add(this);
}
}
IHttpHandler can inject WebSocketHanldler (Extension Method for Context)
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
{
context.AcceptWebSocketRequest(new JsonWebSocketHandler());
}
}
JavaScript also need to separate Open and Send
$(function () {
var cn = new WebSocket("ws://localhost/TestJsonWebSocket/jswsh.ashx");
$("#b").click( function ()
{
cn.onmessage = function (msg) {
alert(msg);
}
});
$("#b2").click(function () {
cn.send(window.JSON.stringify({ type: 1 }));
}
);
});
Thursday, December 1, 2011
WebSocket Handler
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment