C#WebSocket.SendAsync()随机卡住

时间:2018-08-19 17:35:01

标签: c# wpf

连接套接字后,我使用以下代码从WPF使用System.Net.WebSocket发送

try
{
    Console.WriteLine("Sending...");
    await _ws.SendAsync(new ArraySegment<byte>(packet.GetBytes()), WebSocketMessageType.Binary, true, CancellationToken.None);
    Console.WriteLine("Sent...");
}
catch(Exception e)
{
    Console.WriteLine(e.Message);
}

通话代码

            if (!ValidateSettings()) return;
            var hostname = TbHostname.Text.Trim();
            var tcpport = TbTcpPort.Text.Trim();

            _ws = new AchiWebSocket();
            _streamTimer = new System.Threading.Timer(async s =>
                {
                    var socket = (AchiWebSocket)s;
                    if (!_semaWs.Wait(0)) return;
                    UpdateBuffer();
                    var buffer = GetFrameBuffer();
                    var packet = new BinaryPacket(buffer.GetBytes());
                    if(socket.WebSocketState == null || socket.WebSocketState == WebSocketState.Closed)
                        await socket.Connect(new Uri("ws://" + hostname + "/superrfb"));
                    try
                    {
                        await socket.SendAsync(packet);
                    }
                    catch(Exception e)
                    {
                        Console.WriteLine("--" + e.Message);
                    }
                    finally
                    {
                        _semaWs.Release();
                    }
                }, _ws, 0, 70);

接收代码(Asp.Net核心)

 public async Task StartReceiveAsync(Action<Packet> onReceive)
        {
            WebSocketReceiveResult result;
            var buffer = new byte[4 * 1024];
            var stream = new MemoryStream();
            do
            {
                result = await _ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                await stream.WriteAsync(buffer, 0, result.Count);
                if (result.EndOfMessage)
                {
                    var packet = BinaryPacket.FromRaw(stream.ToArray());
                    onReceive.Invoke(packet);
                }
            }
            while (!result.CloseStatus.HasValue);
            Dispose();
        }

我确实收到了一些数据,但是套接字在几个数据包之后卡在了SendAsync中。即使等待了几分钟,它也不会返回。

enter image description here

1 个答案:

答案 0 :(得分:0)

好吧,我知道了。我的onReceive.Invoke()函数有时会引发异常,导致服务器停止接收。这使接收缓冲区填满,WebSocket.SendAsync卡住,然后等待缓冲区释放。将onReceive.Invoke()包装在try catch中之后,代码现在可以正常工作了。

try 
{
    onReceive.Invoke(packet);
}
catch(Exception e)
{
    Debug.WriteLine(e.Message);
}