Created
January 25, 2019 02:43
-
-
Save zhuzhonghua/3bba8634b0707413939c5487924ef64d to your computer and use it in GitHub Desktop.
clojure server using java nio
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 srvclj.core | |
(:import [java.nio.channels ServerSocketChannel Selector SelectionKey] | |
[java.nio ByteBuffer] | |
[java.net InetSocketAddress]) | |
(:gen-class)) | |
(def buf (ByteBuffer/allocate 1024)); | |
(def selector (Selector/open)) | |
(def serverChannel (ServerSocketChannel/open)) | |
(.configureBlocking serverChannel false) | |
(def port 8888) | |
(def portAddr (InetSocketAddress. port)) | |
(.bind (.socket serverChannel) portAddr) | |
(.register serverChannel selector SelectionKey/OP_ACCEPT) | |
(println "server started") | |
(defn withAccept [key] | |
(println "a client come in") | |
(let [socketChannel (-> key .channel .accept)] | |
(.configureBlocking socketChannel false) | |
(.register socketChannel selector SelectionKey/OP_READ))) | |
(defn withRead [key] | |
(println "read data") | |
(let [socket-channel (.channel key)] | |
(.clear buf) | |
(.read socket-channel buf) | |
(.flip buf) | |
(println (.getInt buf)))) | |
(defn withUnknown [key] | |
(println "unkonwn type" (.readyOps key))) | |
(while true | |
(if (not= 0 (.select selector 3000)) | |
(let [keys (.selectedKeys selector)] | |
(doseq [key keys] | |
(let [ops (.readyOps key)] | |
(cond | |
(= ops SelectionKey/OP_ACCEPT) (withAccept key) | |
(= ops SelectionKey/OP_READ) (withRead key) | |
:else (withUnknown key)))) | |
(.clear keys)))) | |
(println "end") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment