-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
OwinWebSocketAdapter.cs
209 lines (192 loc) · 6.58 KB
/
OwinWebSocketAdapter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Net.WebSockets;
namespace Microsoft.AspNetCore.Owin;
// http://owin.org/extensions/owin-WebSocket-Extension-v0.4.0.htm
using WebSocketCloseAsync =
Func<int /* closeStatus */,
string /* closeDescription */,
CancellationToken /* cancel */,
Task>;
using WebSocketReceiveAsync =
Func<ArraySegment<byte> /* data */,
CancellationToken /* cancel */,
Task<Tuple<int /* messageType */,
bool /* endOfMessage */,
int /* count */>>>;
using WebSocketSendAsync =
Func<ArraySegment<byte> /* data */,
int /* messageType */,
bool /* endOfMessage */,
CancellationToken /* cancel */,
Task>;
/// <summary>
/// OWIN WebSocket adapter.
/// </summary>
public class OwinWebSocketAdapter : WebSocket
{
private const int _rentedBufferSize = 1024;
private readonly IDictionary<string, object> _websocketContext;
private readonly WebSocketSendAsync _sendAsync;
private readonly WebSocketReceiveAsync _receiveAsync;
private readonly WebSocketCloseAsync _closeAsync;
private WebSocketState _state;
private readonly string _subProtocol;
/// <summary>
/// Initializes a new instance of <see cref="OwinWebSocketAdapter"/>.
/// </summary>
/// <param name="websocketContext">WebSocket context options.</param>
/// <param name="subProtocol">The WebSocket subprotocol.</param>
public OwinWebSocketAdapter(IDictionary<string, object> websocketContext, string subProtocol)
{
_websocketContext = websocketContext;
_sendAsync = (WebSocketSendAsync)websocketContext[OwinConstants.WebSocket.SendAsync];
_receiveAsync = (WebSocketReceiveAsync)websocketContext[OwinConstants.WebSocket.ReceiveAsync];
_closeAsync = (WebSocketCloseAsync)websocketContext[OwinConstants.WebSocket.CloseAsync];
_state = WebSocketState.Open;
_subProtocol = subProtocol;
}
/// <inheritdocs />
public override WebSocketCloseStatus? CloseStatus
{
get
{
object obj;
if (_websocketContext.TryGetValue(OwinConstants.WebSocket.ClientCloseStatus, out obj))
{
return (WebSocketCloseStatus)obj;
}
return null;
}
}
/// <inheritdocs />
public override string CloseStatusDescription
{
get
{
object obj;
if (_websocketContext.TryGetValue(OwinConstants.WebSocket.ClientCloseDescription, out obj))
{
return (string)obj;
}
return null;
}
}
/// <inheritdocs />
public override string SubProtocol
{
get
{
return _subProtocol;
}
}
/// <inheritdocs />
public override WebSocketState State
{
get
{
return _state;
}
}
/// <inheritdocs />
public override async Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken)
{
var rawResult = await _receiveAsync(buffer, cancellationToken);
var messageType = OpCodeToEnum(rawResult.Item1);
if (messageType == WebSocketMessageType.Close)
{
if (State == WebSocketState.Open)
{
_state = WebSocketState.CloseReceived;
}
else if (State == WebSocketState.CloseSent)
{
_state = WebSocketState.Closed;
}
return new WebSocketReceiveResult(rawResult.Item3, messageType, rawResult.Item2, CloseStatus, CloseStatusDescription);
}
else
{
return new WebSocketReceiveResult(rawResult.Item3, messageType, rawResult.Item2);
}
}
/// <inheritdocs />
public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
{
return _sendAsync(buffer, EnumToOpCode(messageType), endOfMessage, cancellationToken);
}
/// <inheritdocs />
public override async Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
{
if (State == WebSocketState.Open || State == WebSocketState.CloseReceived)
{
await CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
}
var buffer = ArrayPool<byte>.Shared.Rent(_rentedBufferSize);
try
{
while (State == WebSocketState.CloseSent)
{
// Drain until close received
await ReceiveAsync(new ArraySegment<byte>(buffer), cancellationToken);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
/// <inheritdocs />
public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
{
// TODO: Validate state
if (State == WebSocketState.Open)
{
_state = WebSocketState.CloseSent;
}
else if (State == WebSocketState.CloseReceived)
{
_state = WebSocketState.Closed;
}
return _closeAsync((int)closeStatus, statusDescription, cancellationToken);
}
/// <inheritdocs />
public override void Abort()
{
_state = WebSocketState.Aborted;
}
/// <inheritdocs />
public override void Dispose()
{
_state = WebSocketState.Closed;
}
private static WebSocketMessageType OpCodeToEnum(int messageType)
{
switch (messageType)
{
case 0x1:
return WebSocketMessageType.Text;
case 0x2:
return WebSocketMessageType.Binary;
case 0x8:
return WebSocketMessageType.Close;
default:
throw new ArgumentOutOfRangeException(nameof(messageType), messageType, string.Empty);
}
}
private static int EnumToOpCode(WebSocketMessageType webSocketMessageType)
{
switch (webSocketMessageType)
{
case WebSocketMessageType.Text:
return 0x1;
case WebSocketMessageType.Binary:
return 0x2;
case WebSocketMessageType.Close:
return 0x8;
default:
throw new ArgumentOutOfRangeException(nameof(webSocketMessageType), webSocketMessageType, string.Empty);
}
}
}