Skip to content
Browse files

Initial commit

  • Loading branch information...
0 parents commit 4b33dc214d322d94527768c674e37a4f2a6a4d26 @cymen committed
Showing with 80 additions and 0 deletions.
  1. +8 −0 .gitignore
  2. +14 −0 README.md
  3. +5 −0 project.clj
  4. +53 −0 src/clojure_netty/core.clj
8 .gitignore
@@ -0,0 +1,8 @@
+/pom.xml
+*jar
+/lib
+/classes
+/native
+/.lein-failures
+/checkouts
+/.lein-deps-sum
14 README.md
@@ -0,0 +1,14 @@
+# clojure-netty
+Playing with netty in Clojure.
+
+## Usage
+lein deps
+lein run
+
+## Source origin
+http://stackoverflow.com/questions/1735776/server-programming-with-clojure
+
+## Netty 3.3.1.Final
+See this blog entry to get netty 3.3.1.Final:
+
+http://blog.cymen.org/2012/03/12/leiningen-and-lein-localrepo-how-to-create-local-maven-repository-for-jar-files/
5 project.clj
@@ -0,0 +1,5 @@
+(defproject clojure-netty "0.0.1-SNAPSHOT"
+ :description "Basic example of using netty with Clojure"
+ :dependencies [[org.clojure/clojure "1.4.0-beta1"]
+ [local.repo/netty "3.3.1.Final"]]
+ :main clojure-netty.core)
53 src/clojure_netty/core.clj
@@ -0,0 +1,53 @@
+(ns clojure-netty.core
+ (:gen-class)
+ (:import
+ [java.net InetSocketAddress]
+ [java.util.concurrent Executors]
+ [org.jboss.netty.bootstrap ServerBootstrap]
+ [org.jboss.netty.channel Channels ChannelPipelineFactory
+ SimpleChannelHandler]
+ [org.jboss.netty.channel.socket.nio NioServerSocketChannelFactory]
+ [org.jboss.netty.buffer ChannelBuffers]))
+
+(declare make-handler)
+
+(defn start
+ "Start a Netty server. Returns the pipeline."
+ [port handler]
+ (let [channel-factory (NioServerSocketChannelFactory.
+ (Executors/newCachedThreadPool)
+ (Executors/newCachedThreadPool))
+ bootstrap (ServerBootstrap. channel-factory)
+ pipeline (.getPipeline bootstrap)]
+ (.addLast pipeline "handler" (make-handler))
+ (.setOption bootstrap "child.tcpNoDelay", true)
+ (.setOption bootstrap "child.keepAlive", true)
+ (.bind bootstrap (InetSocketAddress. port))
+ pipeline))
+
+(defn make-handler
+ "Returns a Netty handler."
+ []
+ (proxy [SimpleChannelHandler] []
+ (channelConnected [ctx e]
+ (let [c (.getChannel e)]
+ (println "Connected:" c)))
+
+ (channelDisconnected [ctx e]
+ (let [c (.getChannel e)]
+ (println "Disconnected:" c)))
+
+ (messageReceived [ctx e]
+ (let [c (.getChannel e)
+ cb (.getMessage e)
+ msg (.toString cb "UTF-8")]
+ (println "Message:" msg "from" c)))
+
+ (exceptionCaught
+ [ctx e]
+ (let [throwable (.getCause e)]
+ (println "@exceptionCaught" throwable))
+ (-> e .getChannel .close))))
+
+(defn -main []
+ (start 5000 make-handler))

0 comments on commit 4b33dc2

Please sign in to comment.
Something went wrong with that request. Please try again.