我正在尝试基于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}))

最佳答案

我最终为字节数组制作了自己的编解码器。
这很简单,但是要想知道如何用它来保持光泽和光泽是很费时的。

(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}))

关于tcp - 使用Aleph的TCP传输长字节,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34496356/

10-16 09:11