Skip to content

Instantly share code, notes, and snippets.

@mikeananev
Created March 30, 2022 09:00
Show Gist options
  • Select an option

  • Save mikeananev/c0fae6fbcd169b897a0b87b76f8aa398 to your computer and use it in GitHub Desktop.

Select an option

Save mikeananev/c0fae6fbcd169b897a0b87b76f8aa398 to your computer and use it in GitHub Desktop.
test cli-extras
(ns org.rssys.swim
(:import (java.net DatagramPacket DatagramSocket SocketTimeoutException InetSocketAddress InetAddress)))
(def host "127.0.0.1")
(def port 5200)
(def socket (DatagramSocket. ^long port))
(def running (atom true))
(def buffer (make-array Byte/TYPE 1024))
(defn parse [packet]
(println "got message:" (String. (.getData packet) 0 (.getLength packet))))
(defn start-receiver []
(while (true? @running)
(let [packet (DatagramPacket. buffer 1024)]
(try
(do
(println "running")
(.setSoTimeout socket 3000)
(.receive socket packet)
(parse packet))
(catch Exception e
(println "got error:" (.getMessage e))))))
(println "server stop."))
(defn send-udp
"Send a short textual message over a DatagramSocket to the specified
host and port. If the string is over 512 bytes long, it will be
truncated."
[^DatagramSocket socket msg ^String host ^long port]
(let [payload (.getBytes msg)
length ^long (min (alength payload) 512)
address (InetAddress/getByName host)
packet (DatagramPacket. payload length address port)]
(.send socket packet)))
(comment
(def send-socket (DatagramSocket.))
(send-udp send-socket "Hello, world!" host port)
(future (start-receiver))
(.close send-socket))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment