我有一个关于如何开始使用 Fulcro 和 Websockets 的基本问题。
i) 我从 Fulcro lein 模板开始。ii) 然后添加websocket客户端和服务器位。iii) 在我的服务器中,我还添加了一个com.fulcrologic.fulcro.networking.websocket-protocols.WSListener
来检测 WS 客户端何时连接。
在WSListener
, 和浏览器的网络控制台之间,我可以看到客户端从未建立 WS 连接。
- Fulcro 如何建立初始 WS 连接?
- 之后,如何使服务器推送到客户端?
客户端.cljs
(ns foo.client
(:require [fulcro.client :as fc]
[foo.ui.root :as root]
[fulcro.client.network :as net]
[fulcro.client.data-fetch :as df]
[com.fulcrologic.fulcro.networking.websockets :as fws]
[com.fulcrologic.fulcro.application :as app]))
;; Neither this nor the below ":websocket (fws/fulcro-websocket-remote {})" works
;; (defonce app (app/fulcro-app {:remotes {:remote (fws/fulcro-websocket-remote {})}}))
(defonce SPA (atom nil))
(defn mount [] (reset! SPA (fc/mount @SPA root/Root "app")))
(defn start [] (mount))
(def secured-request-middleware
;; The CSRF token is embedded via server_components/html.clj
(->
(net/wrap-csrf-token (or js/fulcro_network_csrf_token "TOKEN-NOT-IN-HTML!"))
(net/wrap-fulcro-request)))
(defn ^:export init []
(reset! SPA (fc/make-fulcro-client
{:client-did-mount (fn [foo]
(df/load foo :all-users root/User))
;; This ensures your client can talk to a CSRF-protected server.
;; See middleware.clj to see how the token is embedded into the HTML
:networking {:remote (net/fulcro-http-remote
{:url "/api"
:request-middleware secured-request-middleware})
:websocket (fws/fulcro-websocket-remote {})}}))
(start))
中间件.cljs
(defrecord FooWSListener []
WSListener
(client-added [this ws-net cid]
(println (str "Listener for dealing with client added events." [ws-net cid])))
(client-dropped [this ws-net cid]
(println (str "listener for dealing with client dropped events." [ws-net cid]))))
(def foo-ws-listener (->FooWSListener))
(def websockets' (atom nil))
(defn query-parser [env query] )
(defstate middleware
:start
(let [websockets (fws/start! (fws/make-websockets
query-parser
{:http-server-adapter (get-sch-adapter)
:parser-accepts-env? true
;; See Sente for CSRF instructions
:sente-options {:csrf-token-fn nil}}))
defaults-config (:ring.middleware/defaults-config config)
legal-origins (get config :legal-origins #{"localhost"})]
(fwsp/add-listener websockets foo-ws-listener)
(reset! websockets' websockets)
(-> not-found-handler
(wrap-api "/api")
(fws/wrap-api websockets)
server/wrap-transit-params
server/wrap-transit-response
(wrap-html-routes)
(wrap-defaults defaults-config)
wrap-gzip)))