Techbubbles

WebSockets in ASP.NET 4.5

 

This post discuss about using WebSockets in ASP.NET 4.5. You can read this post to get an understanding about WebSockets. This post shows piece of code which uses WebSockets in ASP.NET 4.5 and the code is related to simple chat application.

The HTML of Web Form chat application looks as below

image 

It contains a text box where you can type your text message and button where it sends a message to the server. You can notice there is <ul> element which shows the list of other messages which are arriving from the server.

Instantiate a W3C WebSocket JavaScript object and pointed to url to establish a connection to WebSockets Server.

image

The url starts with ws which runs on HTTP and pointing to .ashx handler which runs on ASP.NET server.

The Chat Handler code looks as below, The handler code checks whether sender is looking for WebSockets connection.

image

image

AcceptWebSocketRequest is a new method on Context object in ASP.NET 4.5.

ChatHandler is a wrapper API which implements lower level of WebSockets Handler.

The ChatHandler code looks as below

image

Override the OnOpen method in ChatHandler Class as below

image

We are modifying the OnOpen method code by adding the set WebSockets collection variable which contains the set of connection objects.

image

image

chatapp exposes a method BroadCast which accepts string or binary payload and send the message to all the objects in the collection. The payload in this piece of code is a JSON object.

image

Now To handle the messages that coming from the server, we are adding below piece of code in JavaScript by implementing a handler for OnMessage.

image

In above code we are actually parsing the JSON object that coming from server using JSON.parse method.

To send a message from client to server you can use the below code

image

Once this message comes to the server, you can check the type of message and can write the code as below

image

There is a OnClose method which you can override to close your WebSockets connection. For example when user closes the browser this method will fire and closes the connection.

image

When you run the application then output is as below

image


Share this post :





Related Posts:

%d bloggers like this: