Created
June 20, 2017 06:35
-
-
Save peccu/1bef17ba1fb673a2c7a4774bdaed84b3 to your computer and use it in GitHub Desktop.
hunchensocket echo server example https://github.com/joaotavora/hunchensocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
#|-*- mode:lisp -*-|# | |
#| <Put a one-line description here> | |
exec ros -Q -- $0 "$@" | |
|# | |
(progn ;;init forms | |
(ros:ensure-asdf) | |
#+quicklisp (ql:quickload '(:hunchensocket) :silent t) | |
) | |
(defpackage :ros.script.hunchensocket.3706928135 | |
(:use :cl)) | |
(in-package :ros.script.hunchensocket.3706928135) | |
(defparameter *server* nil) | |
(defparameter *port* 12345) | |
(defclass chat-room (hunchensocket:websocket-resource) | |
((name :initarg :name :initform (error "Name this room!") :reader name)) | |
(:default-initargs :client-class 'user)) | |
(defclass user (hunchensocket:websocket-client) | |
((name :initarg :user-agent :reader name :initform (error "Name this user!")))) | |
(defvar *chat-rooms* (list (make-instance 'chat-room :name "/bongo") | |
(make-instance 'chat-room :name "/fury"))) | |
(defun find-room (request) | |
(find (hunchentoot:script-name request) *chat-rooms* :test #'string= :key #'name)) | |
(pushnew 'find-room hunchensocket:*websocket-dispatch-table*) | |
(defun broadcast (room message &rest args) | |
(loop for peer in (hunchensocket:clients room) | |
do (hunchensocket:send-text-message peer (apply #'format nil message args)))) | |
(defmethod hunchensocket:client-connected ((room chat-room) user) | |
(broadcast room "~a has joined ~a" (name user) (name room))) | |
(defmethod hunchensocket:client-disconnected ((room chat-room) user) | |
(broadcast room "~a has left ~a" (name user) (name room))) | |
(defmethod hunchensocket:text-message-received ((room chat-room) user message) | |
(broadcast room "~a says ~a" (name user) message)) | |
(defmacro with-server (&body body) | |
`(tagbody beginning | |
(let* ((*server* (make-instance 'hunchensocket:websocket-acceptor :port *port*))) | |
(hunchentoot:start *server*) | |
(format t "server started~%Now open two browser windows on http://www.websocket.org/echo.html, enter ws://localhost:12345/bongo as the host and play around chatting with yourself.~%") | |
(unwind-protect (handler-bind ((usocket:connection-refused-error | |
(lambda (e) | |
(declare (ignore e)) | |
(sleep 1) | |
(go beginning)))) | |
,@body) | |
(format t "stopping server~%") | |
(hunchentoot:stop *server*) | |
(sleep 0.5))))) | |
(defun main (&rest argv) | |
(declare (ignorable argv)) | |
(with-server | |
(loop (sleep 0.1)))) | |
;;; vim: set ft=lisp lisp: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment