SslStream: using check data available to perform polling IO

1.4k views Asked by At

A while ago i wrote some basic Http webserver in vb.net. I tried to avoid blocking IO, so basically i made one polling thread for all current connections.

While True
    For Each oNetworkstream In lstNetworkstream
        If oNetworkstream.DataAvailable Then
            'Read from stream
        End If
    Next
End While

So whenever a connection had some new data, i could read it, otherwise immediately check the next connection.

Now i'm extending the webserver with https. Therefore, i used the .Net SslStream Class. I would like to apply the same principle (one polling thread to read all streams)

Since there is no .DataAvailable property, i tried width .Length > 0, but this gives a NotSupportedException (This stream does not support seek operations)

Dim oSslStream As New SslStream(oStream, False)
oSslStream.AuthenticateAsServer(moCertificateKeyPair)
MsgBox(oSslStream.Length)

So, how could i determine if a certain decrypted stream has data available without blocking the thread?

1

There are 1 answers

2
usr On

Avoiding blocking is a good idea when you have many connections. But polling is not the way to solve it.

Instead, you should use async IO. Let the system notify you when data is ready.

With C# 5 you should use async/await + ReadAsync. In lower C# versions you should use Task-based IO (IOW still use ReadAsync is available). If it is not available, write your own version. If you can't do that, use BeginRead.