Page 1 of 1

usocket help with loop and with-connected-socket macro

Posted: Sat May 21, 2011 8:21 pm
by georgek
hi, beginner here working on a basic telnet server with usocket. Luckily there are plenty of examples but I'm a little confused by this:

Code: Select all

(defun tcp-server ()
  (with-socket-listener (socket "127.0.0.1" 8888 :element-type '(unsigned-byte 8))
    (loop
       (with-connected-socket (connection (socket-accept socket))
         (format t "Server received connection" )))))
The confusing part is the loop. Here is with-connected-socket from usocket:

Code: Select all

(defmacro with-connected-socket ((var socket) &body body)
  "Bind `socket' to `var', ensuring socket destruction on exit.

`body' is only evaluated when `var' is bound to a non-null value.

The `body' is an implied progn form."
  `(let ((,var ,socket))
     (unwind-protect
         (when ,var
           (with-mapped-conditions (,var)
             ,@body))
       (when ,var
         (socket-close ,var)))))
So from what I can tell, the loop will run (socket-accept socket) either returning a client socket or nothing; if a client connects the format will write a string to the stream, and then the with-connected-socket macro will close the client socket, and the loop keeps going, looping until the next connection as before.

Is that right? The macros make it all a little magical to me :).

Re: usocket help with loop and with-connected-socket macro

Posted: Sat May 21, 2011 11:48 pm
by ramarren
georgek wrote: either returning a client socket or nothing
The socket-accept function will wait until a connection is received or until it is interrupted, it will never return nothing. Other than that, you are essentially correct. The WITH- macro family is used to guarantee than an initialized resource will be destroyed properly.