WebSocketListener icon indicating copy to clipboard operation
WebSocketListener copied to clipboard

Concurrent CreateMessageWriter for Text

Open chachew opened this issue 7 years ago • 2 comments

I am working in VB.net and need to concurrently send data to the socket as data is collected. I am getting into a scenario where the socket is busy and cant write to it so it kills the connection. Can i write to the socket concurrently or wait until the socket is NOT busy and THEN write to it?

Parallel.ForEach(_datasets, Function(currentSet)
                                                                Console.WriteLine("Starting " + currentSet)
                                                                Dim data As String = _handler.getServerDataset(currentSet)
                                                                Using messageWriterStream As WebSocketMessageWriteStream = ws.CreateMessageWriter(WebSocketMessageType.Text)
                                                                    Using sw As New StreamWriter(messageWriterStream, Encoding.UTF8)
                                                                        sw.WriteAsync(data)
                                                                    End Using
                                                                End Using

                                                                Console.WriteLine("Stopping " + currentSet)
                                                            End Function)

I am seeing the issue/exception at Using messageWriterStream As WebSocketMessageWriteStream = ws.CreateMessageWriter(WebSocketMessageType.Text)

chachew avatar Nov 02 '17 19:11 chachew

Hi,

Yes, when working with sockets you cannot write or read from different threads at the same time. The best way of acomplish this is by using the producer consumer pattern, for example with the TPL Dataflow library: https://blog.stephencleary.com/2012/11/async-producerconsumer-queue-using.html . Then you can have a BufferBlock<> in which many "producer" threads are adding data, and a single "consumer" that reads from that buffer and writes to the socker.

Cheers.

vtortola avatar Nov 02 '17 23:11 vtortola

So is this still the case if i get rid of the Paralell ForEach loop?

If i just iterate over a list of things to send over the socket in a regulare ForEach loop can i send it like that?

Using messageWriterStream As WebSocketMessageWriteStream = ws.CreateMessageWriter(WebSocketMessageType.Text) Using sw As New StreamWriter(messageWriterStream, Encoding.UTF8) Await sw.WriteLineAsync(data) End Using End Using

Sometimes if multiple end user clients(browsers) connect to the same socket server i get a closed connection.

chachew avatar Dec 11 '17 18:12 chachew