Last active
June 14, 2017 21:27
-
-
Save shlomiv/7639408 to your computer and use it in GitHub Desktop.
a working clojure echo server with netty 4
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
(ns netty4.core | |
(:import [io.netty.bootstrap AbstractBootstrap ServerBootstrap] | |
[io.netty.channel ChannelFuture ChannelInitializer ChannelOption | |
ChannelHandlerContext ChannelInboundHandlerAdapter ChannelHandler] | |
[io.netty.handler.logging LogLevel LoggingHandler] | |
io.netty.buffer.ByteBuf | |
io.netty.channel.socket.SocketChannel | |
io.netty.channel.nio.NioEventLoopGroup | |
io.netty.channel.socket.nio.NioServerSocketChannel | |
java.util.concurrent.atomic.AtomicInteger) | |
(:use [clojure.stacktrace]) | |
(:gen-class)) | |
;; the actual server code | |
(def echo-server-handler | |
(proxy [ChannelInboundHandlerAdapter] [] | |
(channelRead [ctx msg] (.write ctx msg)) | |
(channelReadComplete [ctx] (.flush ctx)) | |
(exceptionCaught [ctx cause] | |
(print-stack-trace cause) | |
(.close ctx) | |
))) | |
(defn -main [] | |
(let [b (ServerBootstrap.) | |
elg1 (NioEventLoopGroup.) | |
elg2 (NioEventLoopGroup.) | |
shutdown #(do (.shutdownGracefully elg1) | |
(.shutdownGracefully elg2))] | |
(-> b | |
(.group elg1 elg2) | |
(.channel io.netty.channel.socket.nio.NioServerSocketChannel) | |
(.option ChannelOption/SO_BACKLOG (int 100)) | |
(.childHandler | |
(proxy [ChannelInitializer] [] | |
(initChannel [ch] | |
(-> ch | |
(.pipeline) | |
(.addLast | |
(into-array ChannelHandler [echo-server-handler])))))) | |
(.bind 2424)) | |
(println b) ; print the server bootstrap object | |
shutdown)) | |
(def terminate-server (-main)) ;; run the server and get back a terminate-server function | |
;; now you can "telnet localhost 2424" and see the echo server working | |
(terminate-server) ;; call to terminate server |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment