javac#sslprintwritersslstream

Wait for \n instead of EOF C# SslStream


I'm using SslStream to accept clients. This code reads 2048 bytes from the socket and returns them as a String. When I tried to connect using a client I wrote in Java, the server did not reply and was stuck on this line:

bytes = sslStream.Read(buffer, 0, buffer.Length);

After a bit of googling, I found out that the server is waiting for EOF to complete the message. This is very annoying since the protocol I built needs to wait for \n at the end of the message.

Is there a way to wait for a character of my choosing to complete the message? I tried to add EOF at the end of the message sent by the client, but with no success. I sent the message via PrintWriter. I created it with this statement (Java):

out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));

socket is SSLSocket. The answers I found online were a bit confusing and did not solve my problem.

Server:

static string ReadMessage(SslStream sslStream) 
{
    // Read the  message sent by the client.
    // The client signals the end of the message using the
    // "<EOF>" marker.
    byte[] buffer = new byte[2048];
    StringBuilder messageData = new StringBuilder();
    int bytes = -1;
    do 
    {
        // Read the client's test message.
        bytes = sslStream.Read(buffer, 0, buffer.Length);

        // Use Decoder class to convert from bytes to UTF8
        // in case a character spans two buffers.
        Decoder decoder = Encoding.UTF8.GetDecoder();
        char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
        decoder.GetChars(buffer, 0, bytes, chars, 0);
        messageData.Append(chars);

        // Check for EOF or an empty message.
        if (messageData.ToString().IndexOf("<EOF>") != -1)
        {
            break;
        }
    } while (bytes != 0);

    return messageData.ToString();
}

Adding EOF to the end of the message:

out.print(message + (char)-1);

Also, I tried this:

out.print(message + "\r\n\r");

Solution

  • After a bit of googling, I found out that in order to send the final signal, I neet to flush the socket, using out.flush().