Skip to content

Instantly share code, notes, and snippets.

@nizq
Created December 2, 2013 07:47
Show Gist options
  • Select an option

  • Save nizq/7746355 to your computer and use it in GitHub Desktop.

Select an option

Save nizq/7746355 to your computer and use it in GitHub Desktop.
使用netty-4.x的clojure udp服务,根据netty-4.x的java demo程序翻译过来的。
(ns mytest.udp
(:import (java.net InetSocketAddress
InetAddress)
(io.netty.bootstrap Bootstrap)
(io.netty.channel ChannelOption
EventLoopGroup
ChannelHandlerContext
ChannelInitializer
ChannelHandler
SimpleChannelInboundHandler)
(io.netty.channel.nio NioEventLoopGroup)
(io.netty.channel.socket DatagramPacket)
(io.netty.channel.socket.nio NioDatagramChannel)
(io.netty.util CharsetUtil))
(:use [clojure.tools.logging]))
(defn udp-echo
[content]
(let [text (.toString content CharsetUtil/UTF_8)]
(prn (format "Recieved message: %s" text))
text))
(defn make-udp-handler
[handle]
(proxy [SimpleChannelInboundHandler] []
(channelRead0 [context packet]
(let [content (.content packet)]
(handle content)))
(channelReadComplete [context]
(.flush context))
(exceptionCaught [context exception-event]
(warn (.getCause exception-event) "UDP handler caught"))))
(defn udp-server
([] (udp-server {}))
([opts]
(let [opts (merge {:addr (InetAddress/getByName "0.0.0.0")
:port 5140
:handle udp-echo}
opts)
group (NioEventLoopGroup.)
bootstrap (Bootstrap.)
handler (make-udp-handler (:handle opts))
addr (:addr opts)
port (:port opts)]
(doto bootstrap
(.group group)
(.channel NioDatagramChannel)
(.option ChannelOption/SO_BROADCAST true)
(.handler handler))
(let [f (-> bootstrap
(.bind addr port)
(.sync))]
(-> f
(.channel)
(.closeFuture)
(.sync))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment