2017-04-24 299 views
1

我试图从C#控制台应用程序连接到WebSocket API。ClientWebSocket.ConnectAsync崩溃与任何错误信息

我的代码崩溃ConnectAsync方法,它不会落入catch block或给出任何错误。

这里是我的代码

public async System.Threading.Tasks.Task<Details> Get(string locationUid, string eventType) 
{ 
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | 
              SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; 
    var cancellationTokenSource = new CancellationTokenSource(); 
    using (ClientWebSocket clientWebSocket = new ClientWebSocket()) 
    { 
     Uri serverUri = new Uri(Endpoint.WebSocketUrl); 
     try 
     { 
      await clientWebSocket.ConnectAsync(serverUri, cancellationTokenSource.Token); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e); 
      throw; 
     } 

     while (clientWebSocket.State == WebSocketState.Open) 
     { 
      string bodyMessage = $"{{\"locationUid\":\"{locationUid}\",\"eventTypes\":[\"{eventType}\"]}}"; 
      ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(bodyMessage)); 
      await clientWebSocket.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None); 
      ArraySegment<byte> bytesReceived = new ArraySegment<byte>(new byte[1024]); 
      WebSocketReceiveResult result = await clientWebSocket.ReceiveAsync(bytesReceived, CancellationToken.None); 
      var response = Encoding.UTF8.GetString(bytesReceived.Array, 0, result.Count); 
     } 
    } 
    return null; 
} 

应用坠毁await clientWebSocket.ConnectAsync(serverUri, cancellationTokenSource.Token);也不掉落在catch块

我改变connectAsync线如下

clientWebSocket.ConnectAsync(serverUri, cancellationTokenSource.Token).Wait(cancellationTokenSource.Token); 

现在下降抓块以下例外

The request was aborted: Could not create SSL/TLS secure channel.

堆栈跟踪

at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 
    at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization) 
--- 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.Net.WebSockets.ClientWebSocket.<ConnectAsyncCore>d__21.MoveNext() 

然后我说的方法之前,下面一行开始

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | 
                SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; 

新的异常

Unable to connect to the remote server The remote server returned an error: (400) Bad Request.

堆栈跟踪:

at System.Net.WebSockets.ClientWebSocket.<ConnectAsyncCore>d__21.MoveNext() 

    at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 
    at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization) 
--- 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.Net.WebSockets.ClientWebSocket.<ConnectAsyncCore>d__21.MoveNext() 
+0

你有没有解决过这个问题? –

+0

是的。现在发布我的答案。 – HaBo

回答

1

这就是我得到这个工作。

public async Task<string> GetAllAsync(string url, string bodyMessage, 
      Dictionary<string, string> additionalHeaders) 
     { 
      _securityService.SetClientToken().Wait(); 
      ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | 
                SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; 

      var cancellationTokenSource = new CancellationTokenSource(new TimeSpan(1, 1, 0, 0)); 
      using (ClientWebSocket clientWebSocket = new ClientWebSocket()) 
      { 
       Uri serverUri = new Uri(url); 
       clientWebSocket.Options.SetRequestHeader("Authorization", $"Bearer {Endpoint.ClientAccessToken}"); 
       foreach (var additionalHeader in additionalHeaders) 
       { 
        clientWebSocket.Options.SetRequestHeader(additionalHeader.Key, additionalHeader.Value); 
       } 
       try 
       { 
        clientWebSocket.ConnectAsync(serverUri, cancellationTokenSource.Token) 
         .Wait(cancellationTokenSource.Token); 
       } 
       catch (Exception exception) 
       { 
        Console.WriteLine(exception); 
        throw; 
       } 
       while (clientWebSocket.State == WebSocketState.Open) 
       { 
        ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(bodyMessage)); 
        await clientWebSocket.SendAsync(bytesToSend, WebSocketMessageType.Text, true, 
         CancellationToken.None); 
        ArraySegment<byte> bytesReceived = new ArraySegment<byte>(new byte[1024]); 
        WebSocketReceiveResult result = 
         await clientWebSocket.ReceiveAsync(bytesReceived, CancellationToken.None); 
        var response = Encoding.UTF8.GetString(bytesReceived.Array, 0, result.Count); 
        return response; 
       } 
      } 
      return null; 
     }