How to use the data received from ClientWebSocket in C#?

302 Views Asked by At

This is a Windows Form Application that streams data from a specific server using ClientWebSocket in C#.

I'm new to C# so I just copy/pasted codes from somewhere else on how to connect and receive real time updates from the server.

This is the code that handles the process of receiving the data:

        static async Task Receive(ClientWebSocket socket)
        {
            var buffer = new ArraySegment<byte>(new byte[2048]);
            do
            {
                WebSocketReceiveResult result;
                using (var ms = new MemoryStream())
                {
                    do
                    {
                        result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                        ms.Write(buffer.Array, buffer.Offset, result.Count);
                    } while (!result.EndOfMessage);

                    if (result.MessageType == WebSocketMessageType.Close) break;

                    ms.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(ms, Encoding.UTF8))
                    {
                        var receivedMsg = await reader.ReadToEndAsync();
                        StreamsPayload payload = JsonSerializer.Deserialize<StreamsPayload>(receivedMsg);
                        TickerStreamPayload data = payload.data;
                        Console.WriteLine(data.c);

                    }
                }
            } while (true);
        }

payload.data is a JSON object and I am able to use it just fine using the Console.WriteLine.

But my form has a lot of Label controls in it and I want to populate the Text property of each of those Labels into a string from payload.data. I can't seem to find a way on how to do this as I am not able to access the Labels inside the static async Rask Receive method.

For example, I write:

TickerStreamPayload data = payload.data;
MyLabel.Text = data.c;

This doesn't work and it says "An object reference is required for the non-static field, method, or property 'MainForm.MyLabel' ".

So, how do I go about this?

1

There are 1 best solutions below

0
On

I figured out the issue. I just removed the static keyword when declaring the Received(ClientWebSocket) method and I am now able to access the Labels of the form. I don't know why the author of the code I copy/pasted it from used the static keyword but I am glad it is working now.