我正在尝试从C#控制台应用程序连接到WebSocket
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);
现在它正在下降捕获阻止,并带有以下异常
请求已中止:无法创建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()
答案 0 :(得分: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;
}