Skip to content

Instantly share code, notes, and snippets.

@shlomiv
Last active June 14, 2017 21:27
Show Gist options
  • Save shlomiv/7639408 to your computer and use it in GitHub Desktop.
Save shlomiv/7639408 to your computer and use it in GitHub Desktop.
a working clojure echo server with netty 4
(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