I have an SSL connection to a server and post requests to it. The act of posting a message should be instant with no delay to read the response, because there would be consequent posts that should come without the delay.
That's why i just do
this.sslStream.Write(byteArray, 0, byteArray.Length);
However, I need some responses to be actually received by my app, so I have a parallel thread:
this.threadReadStream = new Thread(new ThreadStart(this.ThreadReadStream));
this.threadReadStream.Start();
In that thread I have a loop which reads data from sslStream:
public void ThreadReadStream()
{
int bufferLen = 4096, byteCount, pos, pos2;
var buffer = new byte[bufferLen];
string responseBuffer = "", responsePart, response = "";
bool err = true;
while (true)
{
err = true;
byteCount = 0;
while (err)
{
err = false;
byteCount = 0;
try
{
byteCount = this.sslStream.Read(buffer, 0, bufferLen);
}
catch (Exception exception)
{
err = true;
this.TcpConnect();
}
}
if (byteCount > 0)
{
// do something
}
}
}
The problem is that sslStream.Read always returns 0 while being used in separate thread, but works fine if called in the same thread with sslStream.Write.
Few comments about the things that are not likely to influece the problem, however, it is better to clarify the stuff: 1) I use while(err) cycle to check that the connection was not broken. If so, I reconnect and read again. 2) For the ones who don't like while(true) thing. Yes, I have the exit condition from the loop in the parallel thread which shut downs all the tcp-related threads.