public
Created

Channel based chat example

  • Download Gist
client.scm
Scheme
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
(use unix-sockets channel srfi-18 parley)
 
(define output-channel
(make-channel))
 
(channel-enqueue output-channel (parley "Your name: "))
 
(define-values (in out)
(unix-connect "sock"))
 
(flush-channel-to-output-port
output-channel out write-line)
 
(thread-start!
(lambda ()
(let loop ()
(let ((line (parley "")))
(unless (eof-object? line)
(channel-enqueue output-channel line)
(loop))))))
 
(define-values (next channel)
(siphon-input-port in read-line))
 
(on-channel-receive channel print)
 
(let loop ()
(when (next)
(loop)))
server.scm
Scheme
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
(use unix-sockets channel srfi-18)
 
(define socket-file "sock")
 
(when (file-exists? socket-file)
(delete-file socket-file))
 
(define listener
(unix-listen socket-file))
 
(define broadcast-channel
(make-channel))
 
(on-channel-receive broadcast-channel print)
 
(let loop ()
(define-values (in out) (unix-accept listener))
 
(thread-start!
(lambda ()
(define name (read-line in))
(print name " joined")
 
(flush-channel-to-output-port
broadcast-channel out write-line)
 
(define-values (next channel)
(siphon-input-port in read-line))
 
(siphon-channel
(map-channel
channel
(lambda (message)
(string-append name ": " message)))
broadcast-channel)
 
(let loop ()
(when (next)
(loop)))))
(loop))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.