'why i can't decode a byteReadChannel to a string

am looking to instantly read the recieved bytes from a socket (TCP) and decode it into a string , the problem is i need to wait until the server close the socket to get the recieved message . the code :

                try {
                            val connectedSock = sock.connect(ip,port)

                            launch (Dispatchers.IO) {
                                while (isChecked) {
                                    val receive = connectedSock.openReadChannel()
                                    var receivedMsg = String(receive.toByteArray())
                                    log(receivedMsg.toString())
                                    
                                }
                            }
                            launch {
                                while (isChecked) {
                                    if (!isChecked) {
                                        connectedSock.close()
                                        selectorManager.close()
                                        log("disconnected from server")
                                    }
                                }
                            }
                        }

PS : am trying to create a activity in my app to display message sent by socket(TCP) .

edit : i tryed this :

try {
                            val connectedSock = sock.connect(ip,port)
                            val receive = connectedSock.openReadChannel()
                            launch (Dispatchers.IO) {
                                while (isChecked) {

                                    while(true){
                                        var l = receive.availableForRead
                                        var receivedMsg = receive.readUTF8Line(l).toString()
                                        log(receivedMsg)
                                        logView.append(receivedMsg)
                                    }


                              
                                }
                            }
                            launch {
                                while (isChecked) {
                                    if (!isChecked) {
                                        connectedSock.close()
                                        selectorManager.close()
                                        log("disconnected from server")
                                    }
                                }
                            }
                        }

now i need to wait until i recieve a other string from the server to log the previous , why i can't instantly log the recevied one without waiting another one ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source