(load "~/quicklisp/setup.lisp") (ql:quickload '(:clack :websocket-driver :cl-bcrypt :datafly :sxql :alexandria :com.inuoe.jzon)) (defvar *connections* (make-hash-table)) (defun handle-new-connection (con) (let* ((user (make-hash-table)) (json (make-hash-table))) (setf (gethash "uid" user) (random 100000)) (setf (gethash "x" user) 0.0) (setf (gethash "y" user) 0.0) (setf (gethash "cmd" json) "login") (setf (gethash "user" json) user) (setf (gethash "users" json) *connections*) (websocket-driver:send con (com.inuoe.jzon:stringify json)) (setf (gethash con *connections*) user))) (defun broadcast-to-room (connection message) (loop :for con :being :the :hash-key :of *connections* :do (websocket-driver:send con message))) (defun handle-close-connection (connection) (let ((message (format nil "{\"cmd\":\"logout\", \"uid\":\"~a\"}" (gethash connection *connections*)))) (remhash connection *connections*) (loop :for con :being :the :hash-key :of *connections* :do (websocket-driver:send con message)))) (defun chat-server (env) (let ((ws (websocket-driver:make-server env))) (websocket-driver:on :open ws (lambda () (handle-new-connection ws))) (websocket-driver:on :message ws (lambda (msg) (broadcast-to-room ws msg))) (websocket-driver:on :close ws (lambda (&key code reason) (declare (ignore code reason)) (handle-close-connection ws))) (lambda (responder) (declare (ignore responder)) (websocket-driver:start-connection ws)))) (defvar *server* (clack:clackup #'chat-server :port 12345))