Skip to content

Instantly share code, notes, and snippets.

@rwat
Created August 13, 2010 22:09
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/523629 to your computer and use it in GitHub Desktop.
Save rwat/523629 to your computer and use it in GitHub Desktop.
(import '(java.net InetAddress
InetSocketAddress
DatagramPacket
DatagramSocket))
; Create a SocketAddress object that holds the IP address and UDP port the
; socket will listen to.
(let [listener-ip "127.0.0.1"
listener-port 29000]
(def listener-socket-address (InetSocketAddress. (InetAddress/getByName listener-ip) listener-port)))
; Create the DatagramSocket with the above SocketAddress.
(def listener-sock (DatagramSocket. listener-socket-address))
; Create a DatagramPacket to store received data.
(let [buf-len 1500]
(def datagram-packet (DatagramPacket. (byte-array buf-len) buf-len)))
; Wait for a packet on the socket we created above. It will store the data it
; receives in a DatagramPacket object. Will block the current thread until
; it receives a packet.
(do (.receive listener-sock datagram-packet))
; Do something with the data received.
(prn (String. (.getData datagram-packet)))
; one way to verify operation is to nmap the port:
; nmap -sU -P0 -p 29000 127.0.0.1
@rwat
Copy link
Author

rwat commented Aug 13, 2010

A future goal is to abstract the UDP network operations out to be more functional. The above works but by clojure standards is poorly written.

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