mwh@gradin.cis.upenn.edu (Michael Hicks) writes:
>Olin Shivers (shivers@ai.mit.edu) wrote:
>
>: I've got the following six lines of code running on lambda.ai.mit.edu:
>
>: (bind-listen-accept-loop protocol-family/internet
>: (lambda (sock addr)
>: (write-string "Eat flaming death, earthling.\n"
>: (socket:outport sock))
>: (close-socket sock))
>: 8006)
>: which you can test by saying
>: telnet lambda.ai.mit.edu 8006
>: until I reboot my workstation.
Just for fun and comparison, here's the equivalent using the
object-oriented Scheme in SoftQuad Sculptor. Its socket subsystem
works via callbacks, so this doesn't actually tie up the application:
;;
;; A Rude Server. Rudely refuses connections.
;;
(require "sockconn") ; socket-connection class
((class args
(inherit socket-connection args)
(method (accept-connection sock addr) ;; "sock" is a connect from "addr"
(send-mesg "Eat flaming death, earthling.\n" sock)
#f)) ;; #f means refuse connection, ie close it
'new 8006)
But here's a more interesting one. It's essentially a "wc" service.
Every time you send it a line of text, it sends back the accumulated
character count. The socket-connection class performs the accumulation
of input into packaged lines for you, so there won't be any problems
with fragmented lines:
;;
;; A More Useful Server. Every time you send it a line, it sends you
;; the accumulate character count. A new instance is automatically
;; instantiated for every connection, so this code will correctly
;; handly any number of simultaneous connections.
;;
(require "sockconn") ;; socket-connection class
((class (socket)
(define chars 0) ;; accumulated character count
(inherit socket-connection socket '())
(method (recv-line line)
(set! chars (+ chars (string-length line) 1)) ; +1 for \n
(me 'send-string (format "~a~%" chars))))
'new 8007)
Considerably easier than doing it in C, I'd say.
--
Pontus Hedman, SoftQuad Inc. Voice: +1 416 239-4801x236
rph@sq.com AX25: VE3RPH @ VE3RPI.#SCON.ON.CAN.NOAM
|