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
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.
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.
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
Override the OnOpen method in ChatHandler Class as below
We are modifying the OnOpen method code by adding the set WebSockets collection variable which contains the set of connection objects.
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.
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
Once this message comes to the server, you can check the type of message and can write the code as below
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.
When you run the application then output is as below