Search code examples
kotlintcpnetty

int socket response is not shown by nc


I'm running a simple tcp server at port 8080 with Netty that responds with hello when a connection is made.

class MyHandler : ChannelInboundHandlerAdapter() {

    override fun channelActive(ctx: ChannelHandlerContext) {
        val time = ctx.alloc().buffer(4)
        time.writeBytes("hello".toByteArray())
        val future = ctx.writeAndFlush(time)
        future.addListener(ChannelFutureListener.CLOSE)
    }

}

If I run nc localhost 8080, I get hello response. Everything ok. But when I change my code to respond with 1234 (integer) instead, I get an empty response from nc.

class MyHandler : ChannelInboundHandlerAdapter() {

    override fun channelActive(ctx: ChannelHandlerContext) {
        val time = ctx.alloc().buffer(4)
        time.writeInt(1234) // <-- this is the change
        val future = ctx.writeAndFlush(time)
        future.addListener(ChannelFutureListener.CLOSE)
    }

}

Solution

  • The nc program has no idea that you are sending an integer. So when it receives it, it has no idea what would be an appropriate way to display it.

    If you were expecting to literally see "1234", then you were expecting magic. How could nc know that the data it received was an encoded integer? If you're going to implement a protocol to send data over TCP, you have to implement it on both ends or you will get garbage on the end that doesn't understand the protocol.