June 17, 2016 by Anuraj Estimated read time : 7 mins
This post is to about using WebSockets in your ASP.NET Core application.WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply. In ASP.NET Core Web Sockets is implemented as a middleware, so to use WebSockets in ASP.NET Core, you need to add the reference of WebSockets server package to the references section. And add WebSockets middleware to the configure method and need to handle the web socket requests.
Here is the project.json file.
Now you need modify startup file, configure method to add the sockets to the HTTP Pipeline.
If the request is WebSocket request, handle it otherwise pass the request to the other middlewares. You can get WebSocket object using AcceptWebSocketAsync() method. Once you got the WebSocket object you can check state property of the web socket object. If the state is Open then you can read and write response to the websocket.
The above code will wait for Text Message in the loop, Binary messages also supported by WebSockets. Now to send response, you can use the following code.
For building chat or subscription based applications, you need to store the WebSockets in a collection and can send response to every websockets. Here is the server side code for an echo service using Web Sockets.
Here is the server side code for echo implementation.
As mentioned earlier, for implementing a chat, you need to add the websockets to a collection and send responses to every sockets. Here is a minimal chat implementation, you can use thread safe collections, for sake for simplicity I am using a normal List.