Last active
May 11, 2021 12:12
-
-
Save darkone23/6102537 to your computer and use it in GitHub Desktop.
websocket as a cljs core.async channel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns example.net | |
(:require [goog.net.WebSocket] | |
[goog.events :refer (listen)] | |
[cljs.core.async :as async :refer (chan <! >! put! close)] | |
[cljs.core.async.impl.protocols :as proto]) | |
(:require-macros [cljs.core.async.macros :refer (go)])) | |
(defn ws | |
"WebSocket as a core.async channel | |
returns a channel which delivers the ws chan then closes" | |
[url] | |
(let [socket (new goog.net.WebSocket) | |
[read write opener] (repeatedly 3 chan) | |
ws-chan (reify | |
proto/ReadPort | |
(take! [_ fn-handler] | |
(proto/take! read fn-handler)) | |
proto/WritePort | |
(put! [_ val fn-handler] | |
(proto/put! write val fn-handler)) | |
proto/Channel | |
(close! [_] | |
(do (proto/close! read) | |
(proto/close! write) | |
(.close socket))))] | |
(go | |
(while true (.send socket (<! write)))) | |
(listen socket goog.net.WebSocket.EventType.MESSAGE | |
(fn [evt] (put! read (.-message evt)))) | |
(listen socket goog.net.WebSocket.EventType.OPENED | |
(fn [evt] (go (>! opener ws-chan) (close! opener)) | |
(.open socket url) | |
opener)) | |
(comment ;; example usage | |
(go | |
(let [ws-chan (<! (ws "ws://localhost:8080/ws"))] | |
(>! ws-chan "Hello, remote server!") | |
(js/console.log (<! ws-chan)))) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment