我有一个使用 WebSocket 进行通信的 Xamarin 应用程序。 在客户端,我引用了 ClientWebSocket。
using (var client = new ClientWebSocket() { Options = { KeepAliveInterval = new TimeSpan(0,0,3,0) }})
{
try
{
await client.ConnectAsync(requestUri, cancellationToken);
do
{
WebSocketReceiveResult result = null;
var buffer = new byte[ReceiveChunkSize];
var message = new ArraySegment<byte>(buffer);
do
{
result = await client.ReceiveAsync(message, cancellationToken);
var receivedMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
data.Append(receivedMessage);
if (result.MessageType != WebSocketMessageType.Text)
break;
} while (!result.EndOfMessage);
TranslateData(data);
} while (client.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested);
该应用程序不断间歇性地抛出了异常:
System.Net.WebSockets.WebSocketException (0x80004005): The remote party closed the WebSocket connection without completing the close handshake.
服务器有一个测试网站,它似乎可以按预期运行。 看来问题出在客户端。 client.State 中的值为 Open。
这是什么问题呢?