我正在尝试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()