Skip to content

Commit 8937ba6

Browse files
add using to sockets sample (dotnet#20301)
* add using to sockets sample * Update aspnetcore/fundamentals/websockets/samples/2.x/WebSocketsSample/Startup2.cs Co-authored-by: Brennan <[email protected]> Co-authored-by: Brennan <[email protected]>
1 parent f84fa4f commit 8937ba6

File tree

3 files changed

+80
-34
lines changed

3 files changed

+80
-34
lines changed

aspnetcore/fundamentals/websockets.md

+10-32
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ description: Learn how to get started with WebSockets in ASP.NET Core.
55
monikerRange: '>= aspnetcore-1.1'
66
ms.author: riande
77
ms.custom: mvc
8-
ms.date: 11/12/2019
8+
ms.date: 11/1/2020
99
no-loc: ["ASP.NET Core Identity", cookie, Cookie, Blazor, "Blazor Server", "Blazor WebAssembly", "Identity", "Let's Encrypt", Razor, SignalR]
1010
uid: fundamentals/websockets
1111
---
@@ -21,40 +21,26 @@ This article explains how to get started with WebSockets in ASP.NET Core. [WebSo
2121

2222
[ASP.NET Core SignalR](xref:signalr/introduction) is a library that simplifies adding real-time web functionality to apps. It uses WebSockets whenever possible.
2323

24-
For most applications, we recommend SignalR over raw WebSockets. SignalR provides transport fallback for environments where WebSockets is not available. It also provides a simple remote procedure call app model. And in most scenarios, SignalR has no significant performance disadvantage compared to using raw WebSockets.
24+
For most applications, we recommend SignalR over raw WebSockets. SignalR provides transport fallback for environments where WebSockets is not available. It also provides a basic remote procedure call app model. And in most scenarios, SignalR has no significant performance disadvantage compared to using raw WebSockets.
25+
26+
For some apps, [gRPC on .NET](xref:grpc/index) provides an alternative to WebSockets.
2527

2628
## Prerequisites
2729

28-
* ASP.NET Core 1.1 or later
29-
* Any OS that supports ASP.NET Core:
30-
30+
* Any OS that supports ASP.NET Core:
3131
* Windows 7 / Windows Server 2008 or later
3232
* Linux
33-
* macOS
34-
33+
* macOS
3534
* If the app runs on Windows with IIS:
36-
3735
* Windows 8 / Windows Server 2012 or later
3836
* IIS 8 / IIS 8 Express
39-
* WebSockets must be enabled (See the [IIS/IIS Express support](#iisiis-express-support) section.).
40-
37+
* WebSockets must be enabled. See the [IIS/IIS Express support](#iisiis-express-support) section.
4138
* If the app runs on [HTTP.sys](xref:fundamentals/servers/httpsys):
42-
4339
* Windows 8 / Windows Server 2012 or later
44-
4540
* For supported browsers, see https://caniuse.com/#feat=websockets.
4641

47-
::: moniker range="< aspnetcore-2.1"
48-
49-
## NuGet package
50-
51-
Install the [Microsoft.AspNetCore.WebSockets](https://www.nuget.org/packages/Microsoft.AspNetCore.WebSockets/) package.
52-
53-
::: moniker-end
54-
5542
## Configure the middleware
5643

57-
5844
Add the WebSockets middleware in the `Configure` method of the `Startup` class:
5945

6046
[!code-csharp[](websockets/samples/2.x/WebSocketsSample/Startup.cs?name=UseWebSockets)]
@@ -99,19 +85,11 @@ Object name: 'HttpResponseStream'.
9985

10086
If you're using a background service to write data to a WebSocket, make sure you keep the middleware pipeline running. Do this by using a <xref:System.Threading.Tasks.TaskCompletionSource%601>. Pass the `TaskCompletionSource` to your background service and have it call <xref:System.Threading.Tasks.TaskCompletionSource%601.TrySetResult%2A> when you finish with the WebSocket. Then `await` the <xref:System.Threading.Tasks.TaskCompletionSource%601.Task> property during the request, as shown in the following example:
10187

102-
```csharp
103-
app.Use(async (context, next) => {
104-
var socket = await context.WebSockets.AcceptWebSocketAsync();
105-
var socketFinishedTcs = new TaskCompletionSource<object>();
106-
107-
BackgroundSocketProcessor.AddSocket(socket, socketFinishedTcs);
88+
[!code-csharp[](websockets/samples/2.x/WebSocketsSample/Startup2.cs?name=AcceptWebSocket)]
10889

109-
await socketFinishedTcs.Task;
110-
});
111-
```
112-
The WebSocket closed exception can also happen if you return too soon from an action method. If you accept a socket in an action method, wait for the code that uses the socket to complete before returning from the action method.
90+
The WebSocket closed exception can also happen when returning too soon from an action method. When accepting a socket in an action method, wait for the code that uses the socket to complete before returning from the action method.
11391

114-
Never use `Task.Wait()`, `Task.Result`, or similar blocking calls to wait for the socket to complete, as that can cause serious threading issues. Always use `await`.
92+
Never use `Task.Wait`, `Task.Result`, or similar blocking calls to wait for the socket to complete, as that can cause serious threading issues. Always use `await`.
11593

11694
## Send and receive messages
11795

aspnetcore/fundamentals/websockets/samples/2.x/WebSocketsSample/Startup.cs

+4-2
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,10 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
7777
{
7878
if (context.WebSockets.IsWebSocketRequest)
7979
{
80-
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
81-
await Echo(context, webSocket);
80+
using (WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync())
81+
{
82+
await Echo(context, webSocket);
83+
}
8284
}
8385
else
8486
{
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#define UseOptions // or NoOptions or UseOptionsAO
2+
using System;
3+
using System.Collections.Generic;
4+
using System.Linq;
5+
using System.Net.WebSockets;
6+
using System.Text;
7+
using System.Threading;
8+
using System.Threading.Tasks;
9+
using Microsoft.AspNetCore.Builder;
10+
using Microsoft.AspNetCore.Hosting;
11+
using Microsoft.AspNetCore.Http;
12+
using Microsoft.Extensions.DependencyInjection;
13+
using Microsoft.Extensions.Logging;
14+
using Microsoft.Extensions.Logging.Console;
15+
using Microsoft.Extensions.Logging.Debug;
16+
17+
namespace EchoApp
18+
{
19+
public class Startup2
20+
{
21+
// This method gets called by the runtime. Use this method to add services to the container.
22+
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
23+
public void ConfigureServices(IServiceCollection services)
24+
{
25+
services.AddLogging(builder =>
26+
{
27+
builder.AddConsole()
28+
.AddDebug()
29+
.AddFilter<ConsoleLoggerProvider>(category: null, level: LogLevel.Debug)
30+
.AddFilter<DebugLoggerProvider>(category: null, level: LogLevel.Debug);
31+
});
32+
}
33+
34+
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
35+
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
36+
{
37+
if (env.IsDevelopment())
38+
{
39+
app.UseDeveloperExceptionPage();
40+
}
41+
42+
#region AcceptWebSocket
43+
app.Use(async (context, next) =>
44+
{
45+
using (WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync())
46+
{
47+
var socketFinishedTcs = new TaskCompletionSource<object>();
48+
49+
BackgroundSocketProcessor.AddSocket(webSocket, socketFinishedTcs);
50+
51+
await socketFinishedTcs.Task;
52+
}
53+
});
54+
#endregion
55+
app.UseFileServer();
56+
}
57+
}
58+
59+
internal class BackgroundSocketProcessor
60+
{
61+
internal static void AddSocket(WebSocket socket, TaskCompletionSource<object> socketFinishedTcs)
62+
{
63+
throw new NotImplementedException();
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)