0

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.

Pingguoren
  • 31
  • 4

1 Answers1

0

How does the server identify that the write process was ended? Maybe there is actually a data on the way to the server so it don't starting to send the response. In addition, sharing a TCP connection between different threads is not a good practice.

BezBran
  • 161
  • 1
  • 8
  • I don't know the server identifies the end of writing. I'm just reading the stream in the loop hoping to catch some data. Actually the response is being sent by the server, it is long to explain how I know that. – Pingguoren May 07 '17 at 13:43