Who created Isockets two minute product video

WebSockets support in ASP.NET Core

  • 3 minutes to read

By Tom Dykstra and Andrew Stanton-Nurse

This article shows you how to get started with WebSockets in ASP.NET. WebSockets (RFC 6455) is a protocol that enables bidirectional persistent communication channels over TCP connections. It is used in apps that benefit from fast, real-time communication, such as chats, dashboards, and game apps.

View or download sample code (download procedure). Run comparison.

SignalR

ASP.NET Core SignalR is a library that makes it easy to add real-time web functionality to apps. It always uses WebSockets whenever possible.

For most applications, we recommend SignalR over RAW WebSockets. SignalR provides transport fallback for environments where WebSockets is not available. In addition, it offers a simple app model for remote procedure calls. Also, in most scenarios, SignalR does not have a significant performance penalty over using RAW WebSockets.

For some apps, gRPC in .NET is an alternative to WebSockets.

requirements

  • Any operating system that ASP.NET Core supports:
    • Windows 7 / Windows Server 2008 and higher
    • Linux
    • macOS
  • If the app is running on Windows with IIS:
  • If the app is running under HTTP.sys:
    • Windows 8 / Windows Server 2012 and higher
  • For more information on supported browsers, see https://caniuse.com/#feat=websockets.

Configure the middleware

Add the WebSockets middleware to the method of the class.

Note

If you want to accept WebSocket requests in a controller, must be called before.

You can configure the following settings:

  • : Determines how often ping frames are sent to the client to ensure that proxies stay connected. The default is two minutes.

You can configure the following settings:

  • : Determines how often ping frames are sent to the client to ensure that proxies stay connected. The default is two minutes.
  • - A list of the allowed Origin header values ​​for WebSocket requests. All origins are allowed by default. See “Restricting WebSocket Origins” below for more information.

Accepting the requests from WebSocket

At a later point in the life cycle of a request (e.g. later in the method or in an action method), check whether it is a WebSocket request and accept it.

The following example is a later excerpt of the method.

WebSocket requests can come in at any URL. However, this sample code only accepts requests for.

When using a WebSocket got to the middleware pipeline will run for the entire duration of the connection. If you try to send or receive a WebSocket message after the middleware pipeline has exited, you might get an exception like the following:

If you are using a background service to write data to a WebSocket, make sure that the middleware pipeline is always running. Use a TaskCompletionSource for this. Pass those to your background service and have them call TrySetResult when you stop the WebSocket. Then use for the Task property during the request as shown in the following example:

The exception "WebSocket closed" can also occur if the return from an action method is too early. When accepting a socket in an action method, wait for the code using the socket to complete before returning from the action method.

Never use, or similar blocking calls to wait for the socket to complete, as this can cause serious threading problems. Always use.

Sending and receiving messages

The method changes the TCP connection to a WebSocket connection and exposes a WebSocket object. Use the object to send and receive messages.

The code shown above that accepts WebSocket requests passes the object to an method. The code receives a message and sends it back immediately. Messages are sent and received in a loop until the client closes the connection:

If you accept the WebSocket connection before the loop begins, the middleware pipeline ends. When you close the socket, the pipeline is unloaded. This means that if the WebSocket is accepted, the request will stop moving in the pipeline. When the loop ends and the socket is closed, the pipeline continues to process the request.

Handle disconnection with the client

The server is not automatically informed if the connection with the client is lost due to loss of connectivity. The server will only receive a disconnection message if the client sends it, which is not possible if the connection is lost. If you want to take action when it does, set a timeout in case no input is received from the client within a certain time window.

If the client isn't always sending messages and you don't want to time out just because the connection goes idle, let the client use a timer to ping every X seconds. If the server does not receive the next message within 2 * X seconds of a message, terminate the connection and report that the client has disconnected. Wait for twice the expected time interval to allow additional time for network delays that could hold up the ping message.

Restriction of WebSocket origins

The protection provided by CORS does not apply to WebSockets. The following applies to browsers Not:

  • Executing CORS preflight requests
  • Be aware of the restrictions specified in the headers when making WebSocket requests

However, browsers send the header when the WebSocket requests are issued. Applications should be configured to check these headers to ensure that only WebSockets from the expected origins are allowed.

If you host your server at https://server.com and your client at https://client.com, add https://client.com to the list for WebSockets to check .

Note

The header is controlled by the client and, like the header, can be tricked. Use these headers Not as an authentication mechanism.

Support for IIS and IIS Express

Windows Server 2012 or higher and Windows 8 or higher with IIS 8 or IIS Express 8 or higher include support for the WebSocket protocol.

Note

WebSockets are always enabled when you use IIS Express.

Enable WebSockets in IIS

To enable support for the WebSocket protocol on Windows Server 2012 or higher:

Note

These steps are not required if you are using IIS Express.

  1. Use the wizard Add roles and features in the menu Manage or the link in Server manager.
  2. click on Role-based or feature-based installation. click on Further.
  3. Select the appropriate server (the local server is selected by default). click on Further.
  4. Expand Web server (IIS) in the structure roll, and expand Web server and subsequently application development.
  5. Choose WebSocket protocol out. click on Further.
  6. If no additional features are required, click Further.
  7. click on To install.
  8. When the installation is complete, click Shut downto exit the wizard.

To enable support for the WebSocket protocol on Windows 8 or higher:

Note

These steps are not required if you are using IIS Express.

  1. Navigate to Control panel > Programs > Programs and Features > Enable or disable Windows features (on the left of the screen).
  2. Open the following nodes: Internet information services > WWW services > Application development features.
  3. Select the feature WebSocket protocol out. click on OK.

Deactivating WebSocket when using "socket.io" in "Node.js"

If you are using WebSocket support in socket.io in Node.js, disable the standard IIS WebSocket module using the element in web.config or applicationHost.config. If this step is not done, the IIS WebSocket module tries to handle the WebSocket communication instead of Node.js and the app.

Sample app

The sample app used in this article is an Echo app. It has a website that makes WebSocket connections. The server sends all received messages back to the client. The sample app is not configured to run with IIS Express through Visual Studio. So run the app in a command shell and navigate to in a browser. The connection status is displayed on the website:

click on Connect (Connect) to send a WebSocket request to the URL shown. Enter test text and click Send (Send). When it's done, click Close socket (Close socket). The section Communication protocol reports every open, send and close action when it is performed.