[usocket-devel] with-* style macros for sockets
Harold Lee
harold at hotelling.net
Tue Jan 23 20:04:22 UTC 2007
Hi,
I've just started using usocket, and it is very nice. The first thing I
did was to write a couple of helper macros for server-side socket
handling, and I thought they might be worth including in the library:
(defmacro with-listener (socket-specs &rest body)
"Listen for connections and clean up when done."
(destructuring-bind (socket-var &rest socket-options) socket-specs
(let ((var-name (gensym)))
`(let* ((,var-name (socket-listen , at socket-options))
(,socket-var ,var-name))
(unwind-protect (progn , at body)
(socket-close ,var-name))))))
(defmacro with-client-stream (socket-specs &rest body)
"Work with a client socket stream and clean up when done."
(destructuring-bind (stream-var listener-var &rest socket-options)
socket-specs
(let ((var-name (gensym)))
`(let* ((,var-name (socket-accept ,listener-var , at socket-options))
(,stream-var (socket-stream ,var-name)))
(unwind-protect (progn , at body)
(socket-close ,var-name))))))
They let you easily get started listening for connections and working
with connected clients (partly because all you see are the listener
socket and a stream for each client). e.g.
(defun handle-one-request ()
(with-listener (listener "127.0.0.1" 40389)
(with-client-stream (stream listener)
(handle-request stream))))
-Harold
More information about the usocket-devel
mailing list