Created
April 5, 2017 10:44
-
-
Save codingtim/a5df555c75c4172ea8ff4701e0cba8b7 to your computer and use it in GitHub Desktop.
Simple udp server with netty 4.1 and kotlin
This file contains 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 characters
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