2012/05/26

usocket の使い方をすっかり忘れてしまっていた

サーバ側

(defparameter *port* 1958)

(defgeneric server-start (server))
(defgeneric server-stop (server))


(defclass* server ()
((host usocket:*wildcard-host*)
(port *port*)
(listen-thread nil)))

(defmethod server-start ((server server))
(setf (listen-thread-of server)
(sb-thread:make-thread
(lambda ()
(usocket:with-socket-listener (socket (host-of server) (port-of server) :reuse-address t)
(loop (usocket:with-connected-socket (connected-socket
(usocket:socket-accept socket))
(let ((stream (usocket:socket-stream connected-socket)))
(print (eval (read stream)) stream)
(force-output stream))))))
:name "nunumo:server")))

(defmethod server-stop ((server server))
(sb-thread:terminate-thread (listen-thread-of server))
(setf (listen-thread-of server) nil))

クライアント側

(defgeneric client-open (client))
(defgeneric client-close (client))
(defgeneric client-read (client))
(defgeneric client-write (client object))
(defgeneric client-flush (client))

(defclass* client ()
((host "localhost")
(port *port*)
(socket nil)
(stream nil)))

(defmethod client-open ((client client))
(setf (socket-of client)
(usocket:socket-connect (host-of client) (port-of client))
(stream-of client)
(usocket:socket-stream (socket-of client)))
client)

(defmethod client-close ((client client))
(force-output (stream-of client))
(usocket:socket-close (socket-of client))
client)

(defmethod client-read ((client client))
(read (stream-of client)))

(defmethod client-write ((client client) object)
(print object (stream-of client)))

(defmethod client-flush ((client client))
(force-output (stream-of client))
client)

はい。RPC システム完成!

(let ((server (make-instance 'server))
(client (make-instance 'client)))
(server-start server)
(unwind-protect
(progn
(client-open client)
(client-write client '(format nil "(+ 1 2) => ~a" (+ 1 2)))
(client-flush client)
(client-read client))
(server-stop server)))
;;=> "(+ 1 2) => 3"

0 件のコメント: