Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rwat
Created October 13, 2010 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwat/624930 to your computer and use it in GitHub Desktop.
Save rwat/624930 to your computer and use it in GitHub Desktop.
(import '(java.net InetAddress
InetSocketAddress
DatagramPacket
DatagramSocket))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; networking
(defrecord UDPServer [dgram-socket connected closed])
(defn create-udp-server
"Uses parameters local-ip and local-port and returns a udp-server record."
[^String local-ip, local-port]
(let [sa (InetSocketAddress. (InetAddress/getByName local-ip) local-port)]
(UDPServer. (DatagramSocket. sa)
true
false)))
(defn udp-listen
[udp-server]
(let [buf-len 1500
datagram-packet (DatagramPacket. (byte-array buf-len) buf-len)
listen (fn [] (do
(.receive (:dgram-socket udp-server) datagram-packet)
(String. (.getData datagram-packet))))]
(do (listen))))
(defn udp-send
[udp-server ^String message]
(comment The message will be padded on the right side with null bytes.
Location of first null + 1 is length of string)
(let [length (.length (.trim message))]
(.send (:dgram-socket udp-server) (DatagramPacket. (.getBytes message) length))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Creates two UDP sockets, a listener and a sender. Simply collect packet
; data from the listener and send data via the sender.
; Leaks memory even when just the listener is listening but the sender is
; not being called.
(def listener (create-udp-server "127.0.0.1" 514 running))
(def sender (create-udp-server "10.0.0.1" 514 running))
(def process (agent nil))
(loop []
(send-off process (fn [_] (udp-send sender (udp-listen listener))))
(recur))
@rwat
Copy link
Author

rwat commented Oct 15, 2010

Problem solved by amalloy on IRC (at this time the code above is still broken, though). Calling send-off on an agent without letting the agent finish things first was causing the memory "leak" or the inability for the queue list of things the agent was working on to get gc'ed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment