The NetworkStream.DataAvailable property does not return the correct result when using SslStream

I have an application with a persistent socket (it opens when the application starts and closes with the application).

This socket is used by the server to enter some data.

Since this connection can be either HTTP or HTTPS, I wrote this code to initialize my objects:

s_tcpClient = new TcpClient(s_server.CometIp, s_server.CometPort);
s_tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, false);
s_tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, CST_STREAM_BUFFER_SIZE);
s_tcpClient.ReceiveTimeout = 0;

s_networkStream = s_tcpClient.GetStream();

s_cometStreamReader = null;

if (s_server.Protocol == "HTTPS")
{
    SslStream sslStream = new SslStream(
        s_tcpClient.GetStream(),
        false,
        new RemoteCertificateValidationCallback(ValidateServerCertificate)
    );

    sslStream.AuthenticateAsClient(s_server.CometIp);
    s_cometStreamReader = new StreamReader(sslStream, Encoding.UTF8, true, CST_STREAM_BUFFER_SIZE);
    s_cometStream = sslStream as Stream;
}
else
{
    s_cometStreamReader = new StreamReader(s_networkStream, Encoding.UTF8, true, CST_STREAM_BUFFER_SIZE);
    s_cometStream = s_networkStream as Stream;
}

This way I can handle the HTTP and HTTPS protocols.

Then I have this loop (in the stream) that expects the data to be available on the socket:

while (s_networkStream.DataAvailable)
{
    numberOfBytesRead = s_cometStream.Read(buffer, 0, buffer.Length);
    message.Append(Encoding.UTF8.GetString(buffer, 0, numberOfBytesRead));
    ExtractMessages(ref message);
}

Here are my 2 questions:

  • , Read 0, . , > 0 ( ), , ... ? Read Read 0?

  • HTTP, . , (CST_STREAM_BUFFER_SIZE), DataAvailable , . HTTPS, , , . , Read CST_STREAM_BUFFER_SIZE, DataAvailable , , , . "" , DataAvailable . ? DataAvailable ?

.

+3
1

0, , , , -. - , , , . CanTimeout , , ReadTimeout - .

, / , , .

http://msdn.microsoft.com/en-us/library/system.io.stream.readtimeout.aspx

+2

Source: https://habr.com/ru/post/1790016/


All Articles