Skip to content

Instantly share code, notes, and snippets.

@andrewhavck
Created December 11, 2013 05:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewhavck/7905572 to your computer and use it in GitHub Desktop.
Save andrewhavck/7905572 to your computer and use it in GitHub Desktop.
async channels with udp
(ns udp-ping.core
(:require [clojure.core.async :refer [>! <! chan go close! thread]])
(:import (java.net DatagramPacket InetAddress MulticastSocket)))
(def port 10001)
(def group (InetAddress/getByName "224.1.0.0"))
(def buffer-size 1000)
(defprotocol Socket
(send! [this msg])
(receive! [this])
(close [this]))
(defrecord Multicast [socket]
Socket
(send! [_ msg] (.send socket (DatagramPacket. (.getBytes msg) (.length msg) group port)))
(receive! [_]
(let [recv (DatagramPacket. (byte-array buffer-size) buffer-size)]
(.receive socket recv)
(String. (.getData recv))))
(close [_] (.close socket)))
(defprotocol Client
(out [this msg])
(in [this]))
(defrecord AsyncClient [in out]
Client
(out [_ msg] (go (>! out msg)))
(in [_] (go (<! in))))
(defn multicast-socket []
(let [socket (MulticastSocket. port)]
(.joinGroup socket group)
(->Multicast socket)))
(defn start []
(let [in (chan)
out (chan)
client (->AsyncClient in out)
socket (multicast-socket)]
(go
(while true
(send! socket (<! out))))
client))
(defn broadcast [msg] (send! (multicast-socket) msg))
(defn read [] (receive! (multicast-socket)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment