我把一个简单的套接字服务器放在一起(见下文).目前,它无法处理多个/并发请求.如何使套接字服务器更高效 – 即能够处理并发请求?我可以利用任何clojure构造吗?到目前为止,我已经考虑过使用
java的NIO(而不是IO)或netty(如
here所指出的那样).
(ns server.policy
(:import
(java.net ServerSocket SocketException)
java.io.PrintWriter))
(defn create-socket
"Creates a socket on given port."
[port]
(ServerSocket. port))
(defn get-writer
"Create a socket file writer."
[client]
(PrintWriter. (.getOutputStream client)))
(defn listen-and-respond
"Accepts connection and responds."
[server-socket service]
(let [client (.accept server-socket)
socket-writer (get-writer client)]
(service socket-writer)))
(defn policy-provider
"Returns domain policy content."
[socket-writer]
(.print socket-writer "<content>This is a test</content>")
(.flush socket-writer)
(.close socket-writer))
(defn run-server
[port]
(let [server-socket (create-socket port)]
(while (not (.isClosed server-socket))
(listen-and-respond server-socket policy-provider))))
最佳答案 我直接使用Netty取得了成功.但是,如果您想要的东西感觉更像是惯用的Clojure代码,请查看
aleph库.它在内部使用Netty,但会产生更简单的代码:
(use 'lamina.core 'aleph.tcp)
(defn echo-handler [channel client-info]
(siphon channel channel))
(start-tcp-server echo-handler {:port 1234})