3

I've written a very simple broadcast/echo server that uses web sockets with clojure and aleph.

I spent a lot of time looking through the aleph and lamina sources to get a decent, basic understand what's happening here.

What I want to do

  1. Establish connections from clients
  2. Send occasional instructions to the server
  3. The instructions are executed and a response is sent to others based on some meta-data about the connection

So this can process the data (which is great) and format the response (which is great). How can I get it to send the response only to relevant parties?

What I have so far

(defn do-something
  [arg]
  (str "pickles" "are" "nice" arg))

(defn ws-handler [ch request]
  (siphon (map* #(do-something %) ch) broadcast-channel)
  (siphon broadcast-channel ch))

(defn -main
  "Start the http server"
  [& args]
  (start-http-server ws-handler {:port 8080 :websocket true}))

Example Request

Let's say I had this request in JSON:

{"room":32, "color":"red", "command":"do something..."}

I would want this to execute the "do something..." command, then the resultant output would be sent to everyone else whose most recent command had included {"room":32, "color":"red"}.

I don't understand how to manage connections this way in aleph... any help?

4

2 回答 2

3

如果您想要更细化谁接收什么消息,您需要比“广播频道”更细化的东西。Lamina 提供了一个(named-channel ...)功能,允许您创建自己的通道命名空间。

这看起来像:

(defn broadcast [channel-name message]
  (enqueue (named-channel channel-name nil) message))

(defn subscribe [channel-name client-channel]
  (let [bridge-channel (channel)]
    (siphon 
      (named-channel channel-name nil)
      bridge-channel
      client-channel)
    #(close bridge-channel)))

在这种情况下,该subscribe方法确保客户端连接将接收来自该特定通道的所有消息,并返回将取消该订阅的函数。您需要有一些每个客户端的状态来保存这些取消回调,但我将把它作为练习留给读者。

于 2013-05-15T17:46:45.600 回答
0

您可以尝试以下方法:

(defn ws-handler [ch request]
  (let [last-msg (atom nil)]
    (siphon (map* #(do (swap! last-msg (constantly %))  [% (do-something %)]) ch) broadcast-channel)
    (siphon (map* second (filter* (fn [[msg v]] (= @last-msg msg)) broadcast-channel)) ch)))
于 2013-05-15T17:48:15.673 回答