如何管理多个连接?

时间:2012-06-05 18:20:46

标签: clojure

我把一个简单的套接字服务器放在一起(见下文)。目前,它无法处理多个/并发请求。如何使套接字服务器更高效 - 即能够处理并发请求?我可以利用任何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))))

1 个答案:

答案 0 :(得分:2)

我直接使用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})

此外,请记住sometimes除了aleph文档之外,您还需要参考lamina文档。