ASP.NET Core 1.1 introduced WebSockets support. Learn how to enable WebSockets in ASP.NET Core and watch a demo of a simple chat/echo program.
- [Narrator] WebSocket support was added in 1.1 and this enables working directly with a socket connection. It requires a Miscrosoft.AspNetCore.WebSockets package and there are three main steps to use this. First configure the middleware, then listen for and accept WebSocket requests, and then send and receive messages. Now SignalR is a much more powerful framework but it does not work with ASP.NET Core 1.0, 1.1, or 2.0.
Let's look at the sample application. Here in my configure method, I've added the package already. On line 115 I say UseWebSockets, and then line 116 to 135 sets up the listener, and anything that comes in on the request path of /ws will then be processed by this method echo. I've also added in UseFileServer because the sample to drive the WebSocket is a straight up HTML file.
If we look at the echo method, it is just processing the WebSocket, and then we look at our socket tester and this is straight from ASP.NET documentation sample. It is just going to put a label up for what it's connected to, and allow you to type a message after opening a connection. Let's switch it back to IS Express just for simplicity, and then we'll run the application and we'll see the WebSocket client in action.
So the file name is called sockettester.html. It's going to be looking for 63812. It dynamically grabs the port we're running. So we'll connect it. We are open. Let's send a message. Send. And all of the test codes spit back out this same message. And then we close the socket. So there ya go, very simple WebSocket support built in to the sample application.
- Running and debugging ASP.NET Core applications
- Pros and cons of migrating existing applications to ASP.NET Core.
- Built-in dependency injection
- Environment awareness and app configuration
- Web host configuration and SSL
- View components invoked as tag helpers
- Configuration and logging
- Using Razor Pages