|
|
|
(in-package :pong.client)
|
|
|
|
|
|
|
|
(defparameter *client* nil)
|
|
|
|
|
|
|
|
(defclass client ()
|
|
|
|
((ip :initarg :ip :initform nil :reader client-ip)
|
|
|
|
(port :initarg :port :initform nil :reader client-port)
|
|
|
|
(running-p :initform nil :accessor client-running-p)
|
|
|
|
(socket :initform nil :accessor client-socket)))
|
|
|
|
|
|
|
|
(defmethod listen-to ((self client))
|
|
|
|
(with-slots (running-p socket) self
|
|
|
|
(when (and running-p (usocket:wait-for-input socket :timeout 5) running-p)
|
|
|
|
(let ((data (cpk:decode-stream (usocket:socket-stream socket))))
|
|
|
|
(format t "[CLIENT] Data received: ~a~%" data)))))
|
|
|
|
|
|
|
|
(defmethod start ((self client))
|
|
|
|
(with-slots (ip port running-p socket) self
|
|
|
|
(format t "uh?~%")
|
|
|
|
(unless running-p
|
|
|
|
(setf running-p t)
|
|
|
|
(setf socket (usocket:socket-connect ip port :element-type 'unsigned-byte)))))
|
|
|
|
|
|
|
|
(defmethod stop ((self client))
|
|
|
|
(with-slots (running-p socket) self
|
|
|
|
(setf running-p nil)
|
|
|
|
(when socket
|
|
|
|
(usocket:socket-close socket))
|
|
|
|
(setf socket nil)))
|
|
|
|
|
|
|
|
(defmethod write-to ((self client) data)
|
|
|
|
(let ((stream (usocket:socket-stream (client-socket self))))
|
|
|
|
(format t "[CLIENT] Data sent: ~a~%" data)
|
|
|
|
(cpk:encode data :stream stream)
|
|
|
|
(force-output stream)))
|
|
|
|
|
|
|
|
(defun handle-client ()
|
|
|
|
(loop while (and *client* (client-running-p *client*))
|
|
|
|
do (let ((data (listen-to *client*))))))
|
|
|
|
|
|
|
|
(defun start-client (ip port)
|
|
|
|
(unless *client*
|
|
|
|
(setf *client* (make-instance 'client :ip ip :port port))
|
|
|
|
(start *client*)
|
|
|
|
(bt:make-thread #'handle-client)))
|
|
|
|
|
|
|
|
(defun stop-client ()
|
|
|
|
(when *client*
|
|
|
|
(stop *client*))
|
|
|
|
(setf *client* nil))
|
|
|
|
|
|
|
|
(defun send-data-to-server (data)
|
|
|
|
(write-to *client* data))
|
|
|
|
|
|
|
|
(defun test-client ()
|
|
|
|
(start-client "127.0.0.1" 54321)
|
|
|
|
(write-to *client* "hello!")
|
|
|
|
(sleep 1.015)
|
|
|
|
(write-to *client* "bye!")
|
|
|
|
(stop-client))
|
|
|
|
|
|
|
|
;; (test-client)
|
|
|
|
|
|
|
|
;; (stop-client)
|
|
|
|
|