Created
February 19, 2012 18:52
-
-
Save thomcc/1865156 to your computer and use it in GitHub Desktop.
sending/receiving UDP messages
This file contains 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 chatty.core | |
(:import [java.net DatagramPacket InetAddress DatagramSocket])) | |
(defn send-data [socket ip port data] | |
(let [ipaddr (InetAddress/getByName ip) | |
pkt (DatagramPacket. (.getBytes data) (count data) ipaddr port)] | |
(.send socket pkt))) | |
(defn receive-data [socket] | |
(let [data (byte-array 1024), pkt (DatagramPacket. data 1024)] | |
(.receive socket pkt) | |
(String. (.getData pkt) 0 (.getLength pkt)))) | |
(defn receiver [port] | |
(let [socket (DatagramSocket. port)] | |
#(receive-data socket))) | |
(defn sender [ip port] | |
(let [socket (DatagramSocket.)] | |
#(send-data socket ip port %))) | |
(def running (atom true)) | |
(defn go [port] | |
(let [recieve-msg (receiver port) | |
send-msg (sender "255.255.255.255" port) | |
fut (future (while @running (println (str "RECEIVED: " (recieve-msg)))))] | |
(println (str "sending/receiving on port " port)) | |
(loop [msg "ping"] | |
(if (= "" msg) | |
(do (println "STOPPING.") | |
(swap! running (constantly false))) | |
(do (println (str "SENDING MESSAGE \"" msg "\".")) | |
(send-msg msg) | |
(recur (read-line))))))) | |
(defn -main [& args] (go 9001)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment