https://kotlinlang.org logo
#ktor
Title
# ktor
c

Colton Idle

03/01/2024, 6:22 AM
I'm trying to use raw sockets in ktor. I can send messages, but I seemingly can't receive them.
readUtf8Line()
never gets called. Ideas?
Copy code
val receiveChannel = socket.openReadChannel()
val sendChannel = socket.openWriteChannel(autoFlush = true)

launch(Dispatchers.IO) {
  while (true) {
    println("awaiting readUtf8Line")
    val greeting = receiveChannel.readUTF8Line()
    if (greeting != null) {
      println(greeting)
    } else {
      print("got a line that's null?")
    }
  }
}
If I instead use my terminal to make a socket connection, I can indeed receive messages. Just looks like something is wrong with receiving in kotlin? Maybe it doesn't like readUTF8Line, but I'm kinda confused on how to use readFully
a

Aleksei Tirman [JB]

03/01/2024, 8:15 AM
Can you share the logic of the other end?
c

Colton Idle

03/04/2024, 3:34 PM
I'm not in control of the other end, but let me see if I can decompile the other code.
Just checked, looks like its not doing anything crazy, just sending a string as utf8.
If I go back to my code and do
Copy code
receiveChannel.read(consumer = { byteBuffer ->
    Log.e("FOO", "Got a message of ${Charsets.UTF_8.decode(byteBuffer)}")
})
then that seems to work fine. but
val greeting = receiveChannel.readUTF8Line()
does not. very weird.
a

Aleksei Tirman [JB]

03/04/2024, 5:15 PM
Can you check that the sent string ends with a line break (
\n
)?
c

Colton Idle

03/04/2024, 5:18 PM
Do you know if it's possible to check that from the byteBuffer?
Do you know if the \n is a standard thing for sockets or something?
a

Aleksei Tirman [JB]

03/04/2024, 5:19 PM
That's just implementation of the
readUTF8Line
which expects the line break.
c

Colton Idle

03/04/2024, 5:20 PM
Gotcha. That's probably it. If I connect to the socket with my macs terminal via netcat (
nc
) then I do not see a /n character.
so thinking about this more. im actually sending json back and forth. so maybe I don't want to actually readUTF8Line, and maybe reading byteBuffer is actually what i want. hmmmm.
2 Views