I'm trying to use raw sockets in ktor. I can send ...
# ktor
c
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
Can you share the logic of the other end?
c
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
Can you check that the sent string ends with a line break (
\n
)?
c
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
That's just implementation of the
readUTF8Line
which expects the line break.
c
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.