Plaster
New
List
Login
common-lisp
default
shinmera
2018.02.21 15:20:11
(ql:quickload '(usocket bordeaux-threads)) (defclass server () ((host :initform "127.0.0.1" :initarg :host :accessor host) (port :initform 1234 :initarg :port :accessor port) (clients :initform () :accessor clients))) (defmethod serve ((server server)) ;; Listen for incoming connections. (let ((server-socket (usocket:socket-listen (host server) (port server)))) (unwind-protect ;; Process each new client that connects. (loop do (process-connection server (usocket:socket-accept server-socket))) (usocket:socket-close server-socket)))) (defmethod process-connection ((server server) socket) (format T "~&New client: ~a~%" socket) (flet ((handler () ;; Read lines as long as the stream is open (loop with stream = (usocket:socket-stream socket) for line = (read-line stream NIL NIL) while line do (broadcast server line)))) (push socket (clients server)) (bt:make-thread #'handler :initial-bindings `((*standard-output* . ,*standard-output*))))) (defmethod broadcast ((server server) line) (dolist (socket (clients server)) (let ((stream (usocket:socket-stream socket))) (write-line line stream) (finish-output stream)))) (serve (make-instance 'server))
Raw
Annotate
Repaste
Annotations
common-lisp
default
shinmera
2018.02.21 15:24:19
(ql:quickload '(usocket bordeaux-threads)) (defclass client () ((host :initform "127.0.0.1" :initarg :host :accessor host) (port :initform 1234 :initarg :port :accessor port) (socket :initform NIL :accessor socket))) (defmethod connect ((client client)) ;; Connect to the server (let ((socket (usocket:socket-connect (host client) (port client)))) (setf (socket client) socket) (process-connection client socket))) (defmethod process-connection ((client client) socket) (flet ((handler () ;; Read lines as long as the stream is open (loop with stream = (usocket:socket-stream socket) for line = (read-line stream NIL NIL) while line do (format T "~&> ~a~%" line)))) (bt:make-thread #'handler :initial-bindings `((*standard-output* . ,*standard-output*))))) (defmethod broadcast ((client client) line) (let ((stream (usocket:socket-stream (socket client)))) (write-line line stream) (finish-output stream))) (let ((client (make-instance 'client))) (connect client) (loop (broadcast client (read-line))))
Raw
Repaste
text
default
shinmera
2018.02.21 15:49:19
sbcl --load server.lisp sbcl --load client.lisp sbcl --load client.lisp Type stuff in either clients to see it broadcasted.
Raw
Repaste