Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

c# - Implementing WebSocket client in .net core 3.1 using ClientWebSocket class

I'm implementing a simple client in C#/.NET Core 3.1, using ClientWebSocket library provided by Microsoft. While receiving data, I'm passing a cancellation token with 10 sec delay. If I don't receive any message in that duration, websocket goes to Aborted State and I have to connect again.

Can anyone help in this regard?

public async Task Receive()
{
    CancellationTokenSource tokenSource = null;
    WebSocketReceiveResult result = null;
    while(true)
    {
        try
        {
            if (webSocket.State == WebSocketState.Open)
            {
                tokenSource = new CancellationTokenSource(10000);
                var buffer = new ArraySegment<byte>(new Byte[8192]);
                using(var stream = new MemoryStream())
                {
                    do
                    {
                        result = await webSocket.ReceiveAsync(buffer, _cancellationTokenSource.Token);
                        stream.Write(buffer.Array, buffer.Offset, result.Count);
                    } while(!result.EndOfMessage);
                }
            }
            else
            {
                //Need to Handle this scenario
            }
        }
        catch (OpearationCancelledException ex)
        {
            //Handle Exception
        }
    }
}
question from:https://stackoverflow.com/questions/65891911/implementing-websocket-client-in-net-core-3-1-using-clientwebsocket-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...