LISP IO Samples 20120825
Lisp IO 総まとめ-20100205 - Shammerismの内容に一部追加。
File 読み込み
(with-open-file (input-stream "$READ_FILE_NAME" :direction :input) (loop (let ((line (read-line input-stream nil 'eof))) (if (eql line 'eof) (return)) (format t "~A~%" line)))))
(with-open-file (stream path :direction :input) (do ((line ;Value Name (read-line stream nil 'eof) ;Initial Value (read-line stream nil 'eof))) ;Step ((eql line 'eof)) ; Finish Judgement (format t "~A~%" line)))
File 書き出し
(with-open-file (output-stream "$OUTPUT_FILE_NAME" :direction :output) (format output-stream "Hello!"))
File 書き足し
(with-open-file (stream path :direction :output :if-exists :append :if-does-not-exist :error) (format stream "~A~%" "Hello, World!") (format stream "~A~%" "END OF FILE"))
TCP Passive Socket
(defun open-echo-server () (with-open-socket (server :type :stream :connect :passive :local-host "localhost" :local-port 8080 :reuse-address t) (let ((client (accept-connection server))) (format t "> Server received a message: ~%") (do ((line (read-line client nil nil) (read-line client nil nil))) ((or (string-equal line (string '#\Return)) (eql line nil))) (dolist (i (coerce line 'list)) (format t "~:c" i)) (format t "~%")) (format t "> Received Complete...~%") (close client))))
UDP Passive Socket
(let ((server (make-socket :type :datagram :local-host "127.0.0.1" :local-port 7001 :format :binary))) (do () () (multiple-value-bind (buffer length client-ip client-port) (receive-from server 512) (format t "Received data is ~A~%" buffer) (format t "Received data length is ~A~%" length) (format t "SRC-IP addr is ~A~%" client-ip) (format t "SRC-Port is ~A~%" client-port))))
TCP Active Socket
(defun send-message (destination-host destination-port message) (with-open-socket (client :address-family :internet :type :stream :connect :active :remote-host destination-host :remote-port destination-port) (format client message) (format client "~%") (force-output client)))
UDP Active Socket
(let ((client (make-socket :type :datagram))) (multiple-value-bind (char-vector count) (encode-string-to-octets "Test" :external-format :UTF-8) (format t "char-vector is ~A~%" char-vector) (format t "char-vector type is ~A~%" (type-of char-vector)) (format t "count is ~A~%" count) (send-to client char-vector count :remote-host "127.0.0.1" :remote-port 7001))) (quit)