In my application, I use SignalR for messaging through my clients. However, the application has a connection to another server for notifications like this:
var wsURL = (isSecure() ? "wss://" : "ws://") + wsEndpointURI + "?token=" + token + "&lang=" + language
+ "&uid=" + wsUid,
notifierWs = new WebSocket(wsURL);
middlewareNotifierWs.onmessage = function (event) {
var notification = JSON.parse(event.data),
msg = notification.message;
};
I want to make this connection from my Asp.Net application and independently process all incoming messages by clicking them on the correct client. However, I do not consider an example of such an implementation. All the examples that I find relate to connecting to the server from my server to the client. (I should mention that I am not very familiar with asynchronous functions, so maybe I have some errors related to this fact)
Update
From what I found, the best and (possibly) easiest way is ClientWebSocket .
, : Websocket - HttpListener ClientWebSocket
, Websocket , .
public static class Program
{
private static UTF8Encoding encoding = new UTF8Encoding();
public static async Task Connect()
{
ClientWebSocket webSocket = null;
try
{
var url = serverWebSocketConnectionUrl;
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(url), CancellationToken.None);
await Task.WhenAll(OnMessage(webSocket));
}
catch (Exception ex)
{
}
finally
{
if (webSocket != null)
{
webSocket.Dispose();
}
}
}
public static async Task OnMessage(ClientWebSocket webSocket)
{
byte[] buffer = new byte[1024];
while (webSocket.State == WebSocketState.Open)
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty,
CancellationToken.None);
}
else
{
WebSocketNotification notification = Newtonsoft.Json.JsonConvert.DeserializeObject<WebSocketNotification>(Encoding.UTF8.GetString(buffer));
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ReportingHub>();
List<string> userIds = new List<string>();
userIds.Add(notification.Id);
hubContext.Clients.Users(userIds).OnMessage(notification);
}
}
}
}
javascript signalR,
onMessage, signalR. ( , signalR, .)
repHub.client.onMessage = function (notification) {
}
, , :
- .
- onMessage
await Task.WhenAll(OnMessage(webSocket)); var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);- , .
:
, , Connect, websocket , . ( await webSocket.ReceiveAsync). ?
, json WebSocketNotification , javascript onMessage . ?
2
,
repHub.client.onMessage => repHub.client.onmessage
, , , signalR, , camelCase camelCase. ? .
3
try catch OnMessage,
public static async Task OnMessage(ClientWebSocket webSocket)
{
byte[] buffer = new byte[1024];
while (webSocket.State == WebSocketState.Open)
{
try
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty,
CancellationToken.None);
}
else
{
WebSocketNotification notification =
Newtonsoft.Json.JsonConvert.DeserializeObject<WebSocketNotification>(
Encoding.UTF8.GetString(buffer));
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ReportingHub>();
List<string> userIds = new List<string>();
userIds.Add(notification.Id);
hubContext.Clients.Users(userIds).OnMessage(notification);
}
}
catch (Exception ex)
{
var a = ex;
}
}
}
, , Connect ,
An internal WebSocket error occurred. Please see the innerException, if present, for more details.
at System.Net.WebSockets.WebSocketBase.ThrowIfConvertibleException(String methodName, Exception exception, CancellationToken cancellationToken, Boolean aborted)
at System.Net.WebSockets.WebSocketBase.<ReceiveAsyncCore>d__45.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at AthenaWeb.Infrastructure.NotificationWebSocket.<OnMessage>d__3.MoveNext() in C:\Branches\Notifications\trunk\AthenaWeb\Infrastructure\NotificationWebSocket.cs:line 69
, , , .
( ):
? - , ?