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. Instantiate a W3C WebSocket JavaScript object and pointed to url to establish a connection to WebSockets 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. 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 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
Related posts
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.
We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.
Sign in