Skip to content

Commit a090b5d

Browse files
committed
NCSContstans renamed
1 parent 3837295 commit a090b5d

File tree

10 files changed

+149
-19
lines changed

10 files changed

+149
-19
lines changed

src/NetCoreStack.WebSockets.ProxyClient/ClientWebSocketConnector.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public ClientWebSocketConnector(IServiceProvider serviceProvider,
5050
private async Task<WebSocketReceiver> TryConnectAsync(CancellationTokenSource cancellationTokenSource = null)
5151
{
5252
_webSocket = new ClientWebSocket();
53-
_webSocket.Options.SetRequestHeader(SocketsConstants.ConnectorName, InvocatorContext.ConnectorName);
53+
_webSocket.Options.SetRequestHeader(NCSConstants.ConnectorName, InvocatorContext.ConnectorName);
5454
try
5555
{
5656
CancellationToken token = cancellationTokenSource != null ? cancellationTokenSource.Token : CancellationToken.None;
@@ -109,7 +109,7 @@ private ArraySegment<byte> CreateTextSegment(WebSocketMessageContext context)
109109
}
110110

111111
object connectionId = string.Empty;
112-
if (context.Header.TryGetValue(SocketsConstants.ConnectionId, out connectionId))
112+
if (context.Header.TryGetValue(NCSConstants.ConnectionId, out connectionId))
113113
{
114114
var id = connectionId as string;
115115
if (string.IsNullOrEmpty(id))
@@ -119,7 +119,7 @@ private ArraySegment<byte> CreateTextSegment(WebSocketMessageContext context)
119119
}
120120
else
121121
{
122-
context.Header.Add(SocketsConstants.ConnectionId, ConnectionId);
122+
context.Header.Add(NCSConstants.ConnectionId, ConnectionId);
123123
}
124124

125125
return context.ToSegment();
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
using Microsoft.Extensions.Logging;
2+
using Newtonsoft.Json;
3+
using System;
4+
using System.Collections.Generic;
5+
using System.IO;
6+
using System.Net.WebSockets;
7+
using System.Threading;
8+
using System.Threading.Tasks;
9+
10+
namespace NetCoreStack.WebSockets.Internal
11+
{
12+
public class ClientWebSocketReceiver
13+
{
14+
private readonly IServiceProvider _serviceProvider;
15+
private readonly WebSocketReceiverContext _context;
16+
private readonly Action<WebSocketReceiverContext> _closeCallback;
17+
private readonly Action<string> _handshakeCallback;
18+
private readonly ILogger<ClientWebSocketReceiver> _logger;
19+
20+
public ClientWebSocketReceiver(IServiceProvider serviceProvider,
21+
WebSocketReceiverContext context,
22+
Action<WebSocketReceiverContext> closeCallback,
23+
Action<string> handshakeCallback = null)
24+
{
25+
_serviceProvider = serviceProvider;
26+
_context = context;
27+
_closeCallback = closeCallback;
28+
_handshakeCallback = handshakeCallback;
29+
_logger = context.LoggerFactory.CreateLogger<ClientWebSocketReceiver>();
30+
}
31+
32+
public async Task ReceiveAsync()
33+
{
34+
try
35+
{
36+
var buffer = new byte[NCSConstants.ChunkSize];
37+
var result = await _context.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
38+
while (!result.CloseStatus.HasValue)
39+
{
40+
if (result.MessageType == WebSocketMessageType.Text)
41+
{
42+
try
43+
{
44+
var context = result.ToContext(buffer);
45+
if (context.Command == WebSocketCommands.Handshake)
46+
{
47+
_context.ConnectionId = context.Value?.ToString();
48+
_handshakeCallback?.Invoke(_context.ConnectionId);
49+
}
50+
51+
var invocator = _context.GetInvocator(_serviceProvider);
52+
invocator?.InvokeAsync(context);
53+
}
54+
catch (Exception ex)
55+
{
56+
_logger.LogWarning(ex, "{0} Invocator error occurred for message type: {1}", NCSConstants.WarningSymbol, WebSocketMessageType.Text);
57+
}
58+
result = await _context.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
59+
}
60+
61+
if (result.MessageType == WebSocketMessageType.Binary)
62+
{
63+
byte[] binaryResult = null;
64+
using (var ms = new MemoryStream())
65+
{
66+
while (!result.EndOfMessage)
67+
{
68+
if (!result.CloseStatus.HasValue)
69+
{
70+
await ms.WriteAsync(buffer, 0, result.Count);
71+
}
72+
result = await _context.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
73+
}
74+
if (result.EndOfMessage)
75+
{
76+
if (!result.CloseStatus.HasValue)
77+
{
78+
await ms.WriteAsync(buffer, 0, result.Count);
79+
}
80+
}
81+
binaryResult = ms.ToArray();
82+
}
83+
try
84+
{
85+
var context = await result.ToBinaryContextAsync(_context.Compressor, binaryResult);
86+
var invocator = _context.GetInvocator(_serviceProvider);
87+
invocator?.InvokeAsync(context);
88+
}
89+
catch (Exception ex)
90+
{
91+
_logger.LogWarning(ex, "{0} Invocator error occurred for message type: {1}", NCSConstants.WarningSymbol, WebSocketMessageType.Binary);
92+
}
93+
result = await _context.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
94+
}
95+
}
96+
97+
await _context.WebSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
98+
_closeCallback?.Invoke(_context);
99+
}
100+
catch (Exception ex)
101+
{
102+
if (ex is TaskCanceledException)
103+
{
104+
return;
105+
}
106+
107+
var dictionary = new Dictionary<string, string>();
108+
dictionary.Add(nameof(_context.ConnectionId), _context.ConnectionId);
109+
110+
if (_context.InvocatorContext != null)
111+
{
112+
dictionary.Add(nameof(_context.InvocatorContext.ConnectorName), _context.InvocatorContext.ConnectorName);
113+
dictionary.Add(nameof(_context.InvocatorContext.Uri), Convert.ToString(_context.InvocatorContext.Uri));
114+
}
115+
116+
_logger.LogWarning(ex, "{0} receive exception: {1}", NCSConstants.WarningSymbol, JsonConvert.SerializeObject(dictionary));
117+
}
118+
finally
119+
{
120+
_closeCallback?.Invoke(_context);
121+
}
122+
}
123+
}
124+
}

src/NetCoreStack.WebSockets/ConnectionManager.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
using System.Text;
1212
using System.Threading;
1313
using System.Threading.Tasks;
14-
using static NetCoreStack.WebSockets.Internal.SocketsConstants;
14+
using static NetCoreStack.WebSockets.Internal.NCSConstants;
1515

1616
namespace NetCoreStack.WebSockets
1717
{

src/NetCoreStack.WebSockets/DefaultHeaderProvider.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ public void Invoke(IDictionary<string, object> header)
1212
return;
1313
}
1414

15-
if (!header.TryGetValue(SocketsConstants.WSFQN, out object host))
15+
if (!header.TryGetValue(NCSConstants.WSFQN, out object host))
1616
{
17-
header.Add(SocketsConstants.WSFQN, FQNHelper.Name);
17+
header.Add(NCSConstants.WSFQN, FQNHelper.Name);
1818
}
1919
}
2020
}

src/NetCoreStack.WebSockets/Extensions/ByteExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
using System;
22
using System.Linq;
3-
using static NetCoreStack.WebSockets.Internal.SocketsConstants;
3+
using static NetCoreStack.WebSockets.Internal.NCSConstants;
44

55
namespace NetCoreStack.WebSockets
66
{

src/NetCoreStack.WebSockets/Extensions/WebSocketExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ public static string GetConnectionId(this WebSocketMessageContext context)
110110
}
111111

112112
object connectionId = null;
113-
if (context.Header.TryGetValue(SocketsConstants.ConnectionId, out connectionId))
113+
if (context.Header.TryGetValue(NCSConstants.ConnectionId, out connectionId))
114114
{
115115
return connectionId.ToString();
116116
}

src/NetCoreStack.WebSockets/Internal/GZipStreamCompressor.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,13 @@ public async Task<byte[]> DeCompressAsync(byte[] input)
2323
{
2424
using (GZipStream stream = new GZipStream(new MemoryStream(input), CompressionMode.Decompress))
2525
{
26-
byte[] buffer = new byte[SocketsConstants.ChunkSize];
26+
byte[] buffer = new byte[NCSConstants.ChunkSize];
2727
using (MemoryStream memory = new MemoryStream())
2828
{
2929
int count = 0;
3030
do
3131
{
32-
count = await stream.ReadAsync(buffer, 0, SocketsConstants.ChunkSize);
32+
count = await stream.ReadAsync(buffer, 0, NCSConstants.ChunkSize);
3333
if (count > 0)
3434
{
3535
await memory.WriteAsync(buffer, 0, count);

src/NetCoreStack.WebSockets/Internal/SocketsConstants.cs renamed to src/NetCoreStack.WebSockets/Internal/NCSConstants.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
1-
namespace NetCoreStack.WebSockets.Internal
1+
using System;
2+
3+
namespace NetCoreStack.WebSockets.Internal
24
{
3-
public static class SocketsConstants
5+
public static class NCSConstants
46
{
57
public static byte[] Splitter = new byte[] { 0x1f };
68
public const int ChunkSize = 1024 * 4;
79
public const string WSFQN = "X-NetCoreStack-WSHost";
810
public const string CompressedKey = "Compressed";
911
public const string ConnectorName = "ConnectorName";
1012
public const string ConnectionId = "ConnectionId";
13+
14+
// Symbols
15+
public static readonly string CheckMarkSymbol = ((char)0x2713).ToString();
16+
public static readonly string WarningSymbol = ((char)0x26A0).ToString();
1117
}
1218
}

src/NetCoreStack.WebSockets/Internal/WebSocketMiddleware.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,27 +26,27 @@ public async Task Invoke(HttpContext httpContext,
2626
string connectionId = string.Empty;
2727
string connectorName = string.Empty;
2828
StringValues headerValue = "";
29-
if (httpContext.Request.Headers.TryGetValue(SocketsConstants.ConnectorName, out headerValue))
29+
if (httpContext.Request.Headers.TryGetValue(NCSConstants.ConnectorName, out headerValue))
3030
{
3131
connectorName = headerValue.ToString();
3232
}
33-
if (httpContext.Request.Headers.TryGetValue(SocketsConstants.ConnectionId, out headerValue))
33+
if (httpContext.Request.Headers.TryGetValue(NCSConstants.ConnectionId, out headerValue))
3434
{
3535
connectionId = headerValue.ToString();
3636
}
3737

3838
if (string.IsNullOrEmpty(connectorName))
3939
{
40-
if (httpContext.Request.Query.ContainsKey(SocketsConstants.ConnectorName))
40+
if (httpContext.Request.Query.ContainsKey(NCSConstants.ConnectorName))
4141
{
42-
connectorName = httpContext.Request.Query[SocketsConstants.ConnectorName];
42+
connectorName = httpContext.Request.Query[NCSConstants.ConnectorName];
4343
}
4444
}
4545
if (string.IsNullOrEmpty(connectionId))
4646
{
47-
if (httpContext.Request.Query.ContainsKey(SocketsConstants.ConnectionId))
47+
if (httpContext.Request.Query.ContainsKey(NCSConstants.ConnectionId))
4848
{
49-
connectionId = httpContext.Request.Query[SocketsConstants.ConnectionId];
49+
connectionId = httpContext.Request.Query[NCSConstants.ConnectionId];
5050
Guid connectionIdGuid = Guid.Empty;
5151
if (!Guid.TryParse(connectionId, out connectionIdGuid))
5252
{

src/NetCoreStack.WebSockets/Internal/WebSocketReceiver.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public WebSocketReceiver(IServiceProvider serviceProvider,
2626

2727
private async Task InternalReceiveAsync()
2828
{
29-
var buffer = new byte[SocketsConstants.ChunkSize];
29+
var buffer = new byte[NCSConstants.ChunkSize];
3030
var result = await _context.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
3131
while (!result.CloseStatus.HasValue)
3232
{

0 commit comments

Comments
 (0)