#! /bin/sh
exec /usr/local/bin/sizzle -s $0
!#
;; examples/chatserver.scm -- simple chatserver
;;
;; Copyright (C) 2000 Martin Grabmueller <mgrabmue@cs.tu-berlin.de>
;;
;; This is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
;; 
;; This software is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;; 
;; You should have received a copy of the GNU General Public License
;; along with this package; see the file COPYING.  If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.  


(define client-list '())

(define server-socket (socket AF_INET SOCK_STREAM 0))
(bind server-socket INADDR_ANY 5476)
(listen server-socket 16)

(define (find-client fd list)
  (cond ((null? list)
	 #f)
	((= (fileno (car list)) fd)
	 (car list))
	(else (find-client fd (cdr list)))))
      
(define (remove-client fd list)
  (cond ((null? list) '())
	((= fd (fileno (car list))) (remove-client fd (cdr list)))
	(else (cons (car list) (remove-client fd (cdr list))))))

(define (remove-client! fd)
  (set! client-list (remove-client (fileno fd) client-list)))

(define (server-loop server-socket)
  (let ((fdset (cons (fileno server-socket) (map fileno client-list))))
;    (writeln fdset)
  (let ((ret (select
	      fdset
	      '() '() 10 0)))
;    (display "select: ")
;    (display ret)
;    (newline)
    (cond ((= ret (fileno server-socket))
;	   (display "Accepting client\n")
	   (set! client-list (cons (car (accept server-socket)) client-list))
	   (display "$ " (car client-list))
	   (force-output (car client-list))
	   (server-loop server-socket))
	  ((> ret 0)
	   (let ((client (find-client ret client-list)))
	     (if client
		 (let ((line (read-line client)))
		   (if (or (eof-object? line) (string-null? line))
		       (begin
			 (remove-client! client)
			 (close-port client))
		       (begin
			 (for-each (lambda (x)
				     (if (not (eq? x client))
					 (begin
					   (display "\r<" x)
					   (display (fileno x) x)
					   (display "> " x)
					   (display line x) (newline x)
					   (force-output x))))
				 client-list)
			 (display "$ " client)
			 (force-output client))))
			 
		 (display "Hmm, no client found\n")))
	   (server-loop server-socket))
	  ((= ret 0)
	   (display "Timeout in `select'\n")
	   (server-loop server-socket))
	  (else (display "error in `select'\n")
		(server-loop server-socket))))))

(server-loop server-socket)
