1 (in-package :iolib.examples
)
3 ;;;; This file was originally written by Peter Keller (psilord@cs.wisc.edu)
4 ;;;; and this code is released under the same license as IOLib.
6 ;;;; This example implements an IPV4 TCP blocking i/o iterative date
7 ;;;; server which handles one connection and then exits.
9 ;;;; This example is written in a non-conventional style resembling
10 ;;;; that of C. Later programs will deviate from this style and move
11 ;;;; more towards the Common Lisp style.
13 ;;;; This server as it stands has more than a few problems especially
14 ;;;; due to not cleaning up the server socket if the code exits
15 ;;;; poorly, suppose returning to the toplevel when you break into the
16 ;;;; debugger while the server is running.
19 (defun run-ex1-server (&key
(port *port
*))
20 ;; Create a passive (server) TCP socket under IPV4 Sockets meant to
21 ;; be listened upon *must* be created passively. This is a minor
22 ;; deviation from the Berkeley socket interface.
26 :address-family
:internet
28 :external-format
'(:utf-8
:eol-style
:crlf
)
30 (format t
"Created socket: ~A[fd=~A]~%" socket
(socket-os-fd socket
))
34 ;; Bind the socket to all interfaces with specified port.
36 +ipv4-unspecified
+ ; which means INADDR_ANY or 0.0.0.0
39 (format t
"Bound socket: ~A~%" socket
)
43 ;; Convert the sockxet to a listening socket
44 (listen-on socket
:backlog
5)
45 (format t
"Listening on socket bound to: ~A:~A~%"
46 (local-host socket
) (local-port socket
))
50 ;; Block on accepting a connection
51 (format t
"Waiting to accept a connection...~%")
52 (let ((client (accept-connection socket
:wait t
)))
54 ;; When we get a new connection, show who it is from.
55 (multiple-value-bind (who rport
)
57 (format t
"Got a connection from ~A:~A!~%" who rport
))
61 ;; Since we're using a internet TCP stream, we can use format
62 ;; with it. However, we should be sure to call finish-output on
63 ;; the socket in order that all the data is sent. Also, this is
65 (multiple-value-bind (s m h d mon y
)
67 (format t
"Sending the time...")
68 (format client
"~A/~A/~A ~A:~A:~A~%" mon d y h m s
)
69 (finish-output client
))
73 ;; We're done talking to the client.
79 ;; We're done with the server socket too.