Skip to content

Instantly share code, notes, and snippets.

@sithu
Forked from codingtim/UdpServer.kt
Created November 29, 2017 09:29
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sithu/9fbca2073e594c58c386cf7e9625b8d2 to your computer and use it in GitHub Desktop.
Save sithu/9fbca2073e594c58c386cf7e9625b8d2 to your computer and use it in GitHub Desktop.
Simple udp server with netty 4.1 and kotlin
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")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment