Get contents of inputStream to a string

When I connect to a server (TCP) I want to store received message in a string. I tried with read() but it reads one character and returns ASCII values

job = CoroutineScope(IO).launch {
    socket = Socket("192.168.0.11", 4000);
    while(socket.isConnected){
        socket.outputStream.write("Hello from the client!".toByteArray());
        var text : String = socket.inputStream.read().toString()
        Log.d("debug ", " result $text")
        delay(2000)
     }
}

It would be helpful if I could at least know when the server stops sending characters, equaling with null didn’t work. I also tried using reader with readText method instead, but it doesn’t return and just keeps reading/blocking (at least I don’t know how it can return a string value, it only returns when closing the connection).

val text = socket.inputStream.reader().use { reader ->  
    reader.readText()
}

For now I just want to receive a string from the server and log it to the console. The server returns a message after I send a request.

This looks like a design question rather than a coding one.

The problem is: how do you know ‘when the server stops sending characters’, if it keeps the connection open?

You could wait until no characters have been sent for a fixed amount of time. But that would introduce unnecessary latency, and risk premature return when the network is slow.

Better to have some in-band signal: either a delimiter, such as a newline character or zero byte, or precede the message with a character count (which must itself have a fixed size).

Once you decide what sort of signalling to use, you can look at how to implement it.

Once I send a request the server returns a string, but there are no special characters and I don’t know how long the string will be, I didn’t design the server

If you don’t have controll over the server there should be some sort of documentation of the API you use that should explain how strings are ended. There is really no 1 standard way of doing this.
@gidds named the most common options but there is really no way to know this about a random API. The best you can do is look through the API documentation or ask the people who designed the server.

So there’s no way to know when the server sent last byte of a message. I guess it makes sense, but this is my first program that deals with asynchronous communication so there’s a lot to learn. I have short documentation, but the only thing that I see is, that the message always starts with either K or O.