Asp.Net open websocket as a client

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;

       // Show the notification
};

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)
        {
            // Log it
        }
        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));

                // Here I want to get to the signalR context and send my message to the correct user.
                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) {
    // Show the message
}

, , :

  • .
  • 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
            {
                // Receive data on ClientWebSocket as an asynchronous operation
                var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Close)
                {
                    // If the server sends a message with message type for closure close the websocket connection
                    // Could use the CloseOutputAsync : https://stackoverflow.com/questions/26744420/net-websocket-closeoutputasync-vs-closeasync
                    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

, , , . ( ):

? - , ?

+4
1

.

, WebSockets , - WebSocket , , .

, - IIS.

, @user4624881, IAsyncResult.AsyncWaitHandle.WaitOne() .

:

Stream s = this.GetStream();
IAsyncResult ar = s.BeginWrite(data, 0, data.Length, SendAsync, state);
if (!ar.IsCompleted)
    ar.AsyncWaitHandle.WaitOne();
+1

Source: https://habr.com/ru/post/1688018/


All Articles