Created
April 5, 2017 10:44
-
-
Save codingtim/a5df555c75c4172ea8ff4701e0cba8b7 to your computer and use it in GitHub Desktop.
Revisions
-
codingtim created this gist
Apr 5, 2017 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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") } } } }