title: Asp.Net open websocket as a client
body: <p>In my application I use SignalR for messaging through my clients. The application however has a websocket connection to another server for notifications like this:</p>
  
  <pre><code>var wsURL = (isSecure() ? "wss://" : "ws://") + wsEndpointURI + "?token=" + token + "&amp;lang=" + language
           + "&amp;uid=" + wsUid,
      notifierWs = new WebSocket(wsURL);
  
  middlewareNotifierWs.onmessage = function (event) {
     var notification = JSON.parse(event.data),
         msg = notification.message;
  
         // Show the notification
  };
  </code></pre>
  
  <p>What I want to do is to make this connection from my Asp.Net application and handle all the incoming messages myself by pushing them to the correct client. 
  I am not finding however an example of such an implementation. All examples I find are about setting a websocket connection from my server to the client.
  (I have to mention that I am not very familiar with asynchronous functions so possibly I have some errors related to this fact) </p>
  
  <p><strong>Update</strong></p>
  
  <p>From what I have found the best and (possibly) simplest way to go is by <a href="https://msdn.microsoft.com/en-us/library/system.net.websockets.clientwebsocket(v=vs.110).aspx" rel="nofollow noreferrer">ClientWebSocket</a>.</p>
  
  <p>Trying to find some examples I found this: <a href="http://www.c-sharpcorner.com/UploadFile/bhushanbhure/websocket-server-using-httplistener-and-client-with-client/" rel="nofollow noreferrer">Websocket - Server Using HttpListener and Client With ClientWebSocket</a></p>
  
  <p>From this example it seems that I could create a Websocket connection  to the endpoint I want. So that is what I did</p>
  
  <pre><code>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&lt;byte&gt;(buffer), CancellationToken.None);
              if (result.MessageType == WebSocketMessageType.Close)
              {
                  await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty,
                      CancellationToken.None);
  
              }
              else
              {
                  WebSocketNotification notification = Newtonsoft.Json.JsonConvert.DeserializeObject&lt;WebSocketNotification&gt;(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&lt;ReportingHub&gt;();
                  List&lt;string&gt; userIds = new List&lt;string&gt;();
                  userIds.Add(notification.Id);
                  hubContext.Clients.Users(userIds).OnMessage(notification);
              }
          }
      }
  }
  </code></pre>
  
  <p>Inside my javascript file handling the signalR methods I have inserted 
  the onMessage method which should be triggered from signalR. (The same way I have inserted all methods handled by signalR and they work just fine.)</p>
  
  <pre><code>repHub.client.onMessage = function (notification) {
      // Show the message
  }
  </code></pre>
  
  <p>From what I have done the current results are:</p>
  
  <ol>
  <li>My websocket connection opens correctly</li>
  <li>From there my debugger gets into the onMessage of the <code>await Task.WhenAll(OnMessage(webSocket));</code> </li>
  <li>After that my debugger awaits in the row <code>var result = await webSocket.ReceiveAsync(new ArraySegment&lt;byte&gt;(buffer), CancellationToken.None);</code></li>
  <li>When a message is sent from the server my debugging continues correctly with the result.</li>
  </ol>
  
  <hr />
  
  <p>My problems and questions are:</p>
  
  <ol>
  <li><p>At some points is triggered the finally of my <code>Connect</code> method where the websocket gets disposed and my listener is released. (Any messages sent aren't caught anymore from <code>await webSocket.ReceiveAsync</code>). Under what circumstances is this suppose to happen and what should I look for?</p></li>
  <li><p>When the message is received I deserialize the json result to the WebSocketNotification correctly but my javascript function onMessage never triggers. What am I missing?</p></li>
  </ol>
  
  <p><strong>Update 2</strong>
  About the second question I made it work by changing</p>
  
  <pre><code>repHub.client.onMessage =&gt; repHub.client.onmessage
  </code></pre>
  
  <p>I find it king of weird though since my reporting hub which uses signalR had all its methods on the server side as camelCase with first letter capital and all its methods on the client side with simple camelCase. Why this case is different? I would appreciate an answer to that.</p>
  
  <p><strong>Update 3</strong></p>
  
  <p>I inserted a try catch in my OnMessage method like that</p>
  
  <pre><code>    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&lt;byte&gt;(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&lt;WebSocketNotification&gt;(
                              Encoding.UTF8.GetString(buffer));
                      var hubContext = GlobalHost.ConnectionManager.GetHubContext&lt;ReportingHub&gt;();
                      List&lt;string&gt; userIds = new List&lt;string&gt;();
                      userIds.Add(notification.Id);
                      hubContext.Clients.Users(userIds).OnMessage(notification);
  
                  }
              }
              catch (Exception ex)
              {
                  var a = ex;
              }
  
          }
      }
  </code></pre>
  
  <p>From the error I get right before my Connect goes to finally and gets disposed I get the following error and stack trace</p>
  
  <pre><code>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.&lt;ReceiveAsyncCore&gt;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.&lt;OnMessage&gt;d__3.MoveNext() in C:\Branches\Notifications\trunk\AthenaWeb\Infrastructure\NotificationWebSocket.cs:line 69
  </code></pre>
  
  <p>I guess I could should just handle it and probably open the connection again. 
  Now pretty much this is my only question (if there isn't anything else to look for):</p>
  
  <p><strong>Is that the best way to go? Should I check for something more on why my connection closes?</strong></p>