Web sockets
By eidias on (tags: web sockets, categories: tools, web)Web socket is a technology developed to establish a bi-directional communication between client and server, over the web. It works on top of TCP and hopefully will render hacks like long polling obsolete. It’s supported by all modern browsers with 2 exceptions – opera mini and the default android browser (chart can be found here).
Here’s a basic example how to use it along with asp.net 4.5.
First the javascript object:
1: var conn = new WebSocket("ws://localhost/foo");
2:
3: conn.onmessage = function(msg) {
4: // deal with the message
5: };
6:
7: conn.send("Hello from client");
This should be pretty self explanatory. The onmessage is a callback used when a message arrives and when you want to push data to the server, use send();
Now the server side code:
1: public class MySocketHttpHandler : IHttpHandler
2: {
3: public void ProcessRequest(HttpContext context)
4: {
5: if (context.IsWebSocketRequest)
6: {
7: context.AcceptWebSocketRequest(new MySocketHandler());
8: }
9: }
10:
11: //...
12: }
13:
14: public class MySocketHandler : WebSocketHandler
15: {
16: private static WebSocketCollection sockets = new WebSocketCollection();
17:
18: public override void OnOpen()
19: {
20: sockets.Add(this);
21: }
22:
23: public override void OnMessage(string message)
24: {
25: // handle incoming message, then respond:
26: sockets.Broadcast("Hello from server");
27: }
28:
29: public override void OnClose()
30: {
31: sockets.Remove(this);
32: }
33: }
This is the basic usage. If you want to know a bit more on the subject, here is a nice article describing how to create a chat app.
There is another way to use web sockets with asp.net – SignalR. It’s an async library that helps with bi-directional communication between client and server. It uses web sockets if they are available, and if not, falls back to long polling. Using SignalR is beyond the scope of this post, but here is the same example (chat app) but built using SignalR.
Cheers