Anonymous user
Echo server: Difference between revisions
→{{header|Common Lisp}}: added a proper usocket example. Removed my earlier actors-based example
(→{{header|Common Lisp}}: added a proper usocket example. Removed my earlier actors-based example) |
|||
Line 545:
=={{header|Common Lisp}}==
Here is a basic [http://common-lisp.net/project/usocket/ :usocket] example (it should work with any Common Lisp):
<lang lisp>(ql:quickload (list :usocket))
(defpackage :echo (:use :cl :usocket))
(in-package :echo)
(defun read-all (stream)
(loop for char = (read-char-no-hang stream nil :eof)
until (or (null char) (eq char :eof)) collect char into msg
finally (return (values msg char))))
(defun echo-server (port &optional (log-stream *standard-output*))
(let ((connections (list (socket-listen "127.0.0.1" port :reuse-address t))))
(unwind-protect
(loop (loop for ready in (wait-for-input connections :ready-only t)
do (if (typep ready 'stream-server-usocket)
(push (socket-accept ready) connections)
(let* ((stream (socket-stream ready))
(msg (concatenate 'string "You said: " (read-all stream))))
(format log-stream "Got message...~%")
(write-string msg stream)
(socket-close ready)
(setf connections (remove ready connections))))))
(loop for c in connections do (loop while (socket-close c))))))
(echo-server 12321)
</lang>
It's single threaded, so you can't REPL around with a running server. You'll need to start a second Lisp prompt, load the above and
<lang lisp>(defun echo-send (message port)
(with-client-socket (sock str "127.0.0.1" port)
(write-string message str)
(force-output str)
(when (wait-for-input sock :timeout 5)
(coerce (read-all str) 'string))))
(echo-send "Hello echo!" 12321)
</lang>
The return value of that call should be "You said: Hello echo!".
The usocket library notwithstanding, sockets are not a standard part of Common Lisp, but many implementations provide them. Here is a CLISP-specific example: {{works with|CLISP}}
<lang lisp>(defvar *clients* '()
"This is a list of (socket :input status) which is used with
Line 594 ⟶ 636:
(echo-server 12321)</lang>
=={{header|D}}==
|