3

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");
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
IshaySela
  • 143
  • 6
  • You're in control of the `do {} while();`, so what's keeping you from `break` it once you read a `NL`? – dcg Dec 23 '19 at 21:02

1 Answers1

2

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().

IshaySela
  • 143
  • 6
  • The socket you are referring to is the java client socket, correct? Also, a few things you may need to handle in the code above. 1. SslStream.Read can return 0 bytes, make sure to break in that case. 2. I'd strongly recommend using the async version of Read (ReadAsync) especially with client and server interaction. – Justin Kotalik Jan 14 '20 at 16:46
  • It's a client socket indeed, and I will check the async function. Thank you! – IshaySela Jan 15 '20 at 15:35