Skip to content

Instantly share code, notes, and snippets.

@codingtim
Created April 5, 2017 10:44
Show Gist options
  • Save codingtim/a5df555c75c4172ea8ff4701e0cba8b7 to your computer and use it in GitHub Desktop.
Save codingtim/a5df555c75c4172ea8ff4701e0cba8b7 to your computer and use it in GitHub Desktop.

Revisions

  1. codingtim created this gist Apr 5, 2017.
    55 changes: 55 additions & 0 deletions UdpServer.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    import io.netty.bootstrap.Bootstrap
    import io.netty.channel.ChannelHandlerContext
    import io.netty.channel.SimpleChannelInboundHandler
    import io.netty.channel.nio.NioEventLoopGroup
    import io.netty.channel.socket.nio.NioDatagramChannel
    import io.netty.util.CharsetUtil
    import io.netty.util.concurrent.DefaultThreadFactory
    import kotlinx.coroutines.experimental.async
    import kotlinx.coroutines.experimental.newFixedThreadPoolContext


    fun main(args: Array<String>) {
    val port: Int
    if (args.isNotEmpty()) {
    port = Integer.parseInt(args[0])
    } else {
    port = 5514
    }
    DiscardServer(port).run()
    }

    class DiscardServer(private val port: Int) {
    private val acceptFactory = DefaultThreadFactory("accept")
    private val acceptGroup = NioEventLoopGroup(1, acceptFactory)

    @Throws(Exception::class)
    fun run() {
    val b = Bootstrap()
    b.group(acceptGroup)
    .channel(NioDatagramChannel::class.java)
    .handler(Handler())
    b.bind(port).sync()
    }

    fun shutdown() {
    acceptGroup.shutdownGracefully()
    }

    }

    class Handler : SimpleChannelInboundHandler<io.netty.channel.socket.DatagramPacket>() {

    private val coroutineContext = newFixedThreadPoolContext(4, "LogPool")

    override fun channelRead0(ctx: ChannelHandlerContext?, msg: io.netty.channel.socket.DatagramPacket?) {
    if (msg != null) {
    val message = msg.content().toString(CharsetUtil.UTF_8)
    async(coroutineContext) {
    System.err.println(Thread.currentThread().name)
    System.err.println(message + "\r\n")
    }
    }
    }

    }