使用Aleph

时间:2015-12-28 15:37:29

标签: tcp clojure aleph

我正在尝试基于aleph构建RCP服务器。它传递了所有测试,但是当发送或接收的字节数组变大时,字节似乎已损坏。

例如。我试图发送一个长度为2936的字节数组,但我在服务器上只有1024字节

我按照示例对nippy进行了自己的修改。编码和解码将由处理程序自己完成。

(defn wrap-duplex-stream
  [s]
  (let [out (s/stream)]
    (s/connect out s)
    (s/splice out s)))

(defn client
  [host port]
  (d/chain (tcp/client {:host host, :port port})
           #(wrap-duplex-stream %)))

(defn start-server
  [handler port]
  (tcp/start-server
    (fn [s info]
      (handler (wrap-duplex-stream s) info))
    {:port port}))

1 个答案:

答案 0 :(得分:1)

我终于为字节数组制作了自己的编解码器。 这很简单,但要想出如何使用它和光泽和aleph是耗时的

(defn buffer->byte-array [buf-seq]
  (byte-streams/to-byte-array buf-seq))

(defn bytes-codec []
  (reify
    Reader
    (read-bytes [this buf-seq]
      (let [buf-seq (dup-bytes buf-seq)
            byte-arr (buffer->byte-array buf-seq)]
        [true byte-arr nil]))
    Writer
    (sizeof [x]
      nil)
    (write-bytes [x y byte-arr]
      [(ByteBuffer/wrap byte-arr)])))

(def protocol
  (gloss/compile-frame
    (gloss/finite-frame
      :uint32
      (bytes-codec))
    #(nippy/freeze %)
    #(nippy/thaw %)))


(defn wrap-duplex-stream
  [s]
  (let [out (s/stream)]
    (s/connect
      (s/map #(io/encode protocol %) out)
      s)
    (s/splice
      out
      (io/decode-stream s protocol))))

(defn client
  [host port]
  (d/chain (tcp/client {:host host, :port port})
           #(wrap-duplex-stream %)))

(defn start-server
  [handler port]
  (tcp/start-server
    (fn [s info]
      (handler (wrap-duplex-stream s) info))
    {:port port}))