我有Open Web Socket方法
public async Task OpenAsync(string url, string bodyMessage,
Dictionary<string, string> additionalHeaders, IImage imageService)
{
_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)
{
string response = null;
try
{
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]);
byte[] incomingData = new byte[1024];
WebSocketReceiveResult result =
clientWebSocket.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None).Result;
if (result.CloseStatus.HasValue)
{
Console.WriteLine("Closed; Status: " + result.CloseStatus + ", " + result.CloseStatusDescription);
}
else
{
response = Encoding.UTF8.GetString(incomingData, 0, result.Count);
Console.WriteLine("Received message: " + response);
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
if(string.IsNullOrWhiteSpace(response)) continue;
//return response;
var jsonRespone = JsonConvert.DeserializeObject<JObject>(response);
ParkingEvent parkingEvent = jsonRespone != null
? (jsonRespone).ToObject<ParkingEvent>()
: new ParkingEvent();
//await SaveAsync(parkingEvent).ContinueWith(x=> imageService.MediaOnDemand(parkingEvent.Properties.ImageAssetUid, parkingEvent.Timestamp), cancellationTokenSource.Token);
await imageService.MediaOnDemandAsync(parkingEvent.Properties.ImageAssetUid, parkingEvent.Timestamp);
}
}
//return null;
}
我希望此连接处于打开状态并处理收到的任何事件
var jsonRespone = JsonConvert.DeserializeObject<JObject>(response);
ParkingEvent parkingEvent = jsonRespone != null
? (jsonRespone).ToObject<ParkingEvent>()
: new ParkingEvent();
//await SaveAsync(parkingEvent).ContinueWith(x=> imageService.MediaOnDemand(parkingEvent.Properties.ImageAssetUid, parkingEvent.Timestamp), cancellationTokenSource.Token);
await imageService.MediaOnDemandAsync(parkingEvent.Properties.ImageAssetUid, parkingEvent.Timestamp);
问题是当我得到第一个响应并且我处理它时,而第二个响应循环失败。如何保持连接打开并处理通过套接字管道接收的所有事件?