2

在我学习 Clojure 的过程中,我目前面临设置 websocket 通信的问题。经过许多不同的方法后,我最终使用了aleph

我设法实现的目标:

  • 处理新客户端连接
  • 处理客户端断开连接
  • 随意从服务器与客户端交谈

我缺少的是每当一个连接的客户端通过 websocket 发送一些东西时触发一个处理函数的方法。

到目前为止我的代码:

(ns wonders7.core.handler
  (:require [compojure.core :refer :all]
            [compojure.route :as route]
            [ring.middleware.defaults :refer [wrap-defaults site-defaults]]
            [aleph.http :as http]
            [manifold.stream :as stream]
            [clojure.tools.logging :refer [info]]))

(defn uuid [] (str (java.util.UUID/randomUUID)))

(def clients (atom {}))

(defn ws-create-handler [req]
  (let [ws @(http/websocket-connection req)]
    (info "ws-create-handler")
    (stream/on-closed ws #(swap! clients dissoc ws))
    (swap! clients assoc ws (uuid))))

(defroutes app-routes
  (GET "/ws" [] ws-create-handler)
  (route/not-found "Not Found"))

(def app
  (wrap-defaults app-routes site-defaults))

(defn msg-to-client [[client-stream uuid]]
  (stream/put! client-stream "The server side says hello!"))

(defn msg-broadcast []
  (map #(msg-to-client %) @clients))

;(stream/take! (first (first @clients)))
;(http/start-server app {:port 8080})

我用注释掉的 http/start-server aleph 调用启动 Netty 服务器。我还设法通过手动流/获取从客户端获取消息!调用(也被注释掉了)。我需要弄清楚的是,当有东西进来时,如何自动触发这种摄取。

提前感谢您的帮助!

4

2 回答 2

4

您正在寻找的函数是(manifold.stream/consume callback stream),它将为来自流的每条消息调用回调。

于 2014-11-09T10:44:31.213 回答
1

这个例子中,作者使用recieve-alland siphonfrom aleph 来完成一个非常相似的任务,我将大致解释为:

(let [chat (named-channel room (receive-all ch #(println "message: " %)))]
  (siphon chat ch)
于 2014-11-09T09:55:44.517 回答