1

我正在尝试WebSocket从 C# 控制台应用程序连接到 API。

我的代码在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);

现在它下降了catch 块,但有以下异常

请求被中止:无法创建 SSL/TLS 安全通道。

堆栈跟踪

   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;

新异常

无法连接到远程服务器远程服务器返回错误:(400)错误请求。

堆栈跟踪:

   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()
4

1 回答 1

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;
        }
于 2017-09-12T19:56:30.977 回答