Skip to content

Instantly share code, notes, and snippets.

@anthonynsimon
Created July 13, 2018 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonynsimon/4663c3e8cdf6802af1c13bf42d07f811 to your computer and use it in GitHub Desktop.
Save anthonynsimon/4663c3e8cdf6802af1c13bf42d07f811 to your computer and use it in GitHub Desktop.
Try Netty
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.{ChannelOption, ChannelHandlerContext, ChannelInitializer, ChannelInboundHandlerAdapter}
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.channel.group.{ChannelGroup, DefaultChannelGroup}
import io.netty.handler.codec.http.{HttpObjectAggregator, HttpServerCodec}
import io.netty.handler.logging.{LogLevel, LoggingHandler}
import io.netty.channel.ChannelHandler.Sharable
import io.netty.handler.codec.http._
import io.netty.util.ReferenceCountUtil
import io.netty.buffer.Unpooled
@Sharable
class HelloServerHandler extends ChannelInboundHandlerAdapter {
override def channelRead(ctx: ChannelHandlerContext, msg: Object): Unit = {
msg match {
case req: FullHttpRequest =>
val response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer("hello world".getBytes()))
response.headers.set("Content-Type", "text/plain")
response.headers.set("Server", "Netty/4.1")
response.headers.set("Content-Length", "11")
ctx.write(response)
req.release()
case _ => ReferenceCountUtil.release(msg)
}
}
override def channelReadComplete(ctx: ChannelHandlerContext): Unit = {
ctx.flush()
}
override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = {
ctx.close()
}
}
object NettyExample {
def main(args: Array[String]): Unit = {
val master, worker = new NioEventLoopGroup()
try {
new ServerBootstrap()
.group(master, worker)
.channel(classOf[NioServerSocketChannel])
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer[SocketChannel] {
override def initChannel(ch: SocketChannel): Unit = {
ch.pipeline
.addLast(new HttpServerCodec)
.addLast(new HttpObjectAggregator(65536))
.addLast(new HelloServerHandler)
}
})
.bind(8080).sync()
.channel()
.closeFuture().sync()
} finally {
master.shutdownGracefully()
worker.shutdownGracefully()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment