我使用System.Net.WebSockets实现了一个websocket-client与嵌入式设备进行通信。在设备上,libwebsocket库正在使用中。
协议的主要部分是使用JSON字符串实现的,它完美地工作,但也需要一些二进制传输。来自Windows的传出二进制消息在设备上正确接收,但是在传入二进制消息的情况下,在ReceiveAsync()处抛出异常。
我将接收部分实现为调用ReceiveAsync()的异步循环。在传入二进制消息的情况下,抛出带有以下错误代码的WebSocketException:
HResult 0x83760002
E_INVALID_PROTOCOL_FORMAT协议数据格式无效。
我不知道是什么导致它,它在我看到我收到的数据之前抛出。它已经可以从设备接收二进制数据,但这是一个早期的实现,只能回送我发送的数据。
private async void ReceiveLoop(CancellationToken cancellationToken)
{
try
{
List<byte> receivedBytes = new List<byte>();
var buffer = new byte[c_bufferSize];
while (!cancellationToken.IsCancellationRequested)
{
var receiveBuffer = new ArraySegment<Byte>(buffer);
WebSocketReceiveResult result;
result = await _webSocket.ReceiveAsync(receiveBuffer, cancellationToken);
receivedBytes.AddRange(receiveBuffer.Array);
// message is complete, return it
if (result.EndOfMessage)
{
if (result.MessageType == WebSocketMessageType.Text)
{
String receivedString = Encoding.UTF8.GetString(receivedBytes.ToArray());
Debug.Print($"{receivedString}");
Debug.Print($"{receivedString.Length.ToString()}");
WebsocketMessage response = new WebsocketMessage(receivedString);
MessagesSubject.OnNext(response);
}
if (result.MessageType == WebSocketMessageType.Binary)
{
WebsocketMessage response = new WebsocketMessage(receivedBytes.ToArray());
MessagesSubject.OnNext(response);
}
receivedBytes.Clear();
buffer = new byte[c_bufferSize];
}
}
}
catch(OperationCanceledException ex)
{
return;
}
catch(Exception ex)
{
MessagesSubject.OnError(ex);
}
}