09fe137f5ecbba80021996de34377938416e1801
[8sync.git] / demos / websocket / 8s-client.scm
1 #! /usr/bin/env guile
2 # -*-scheme-*-
3 !#
4
5 ;;; 8sync --- Asynchronous programming for Guile
6 ;;; Copyright © 2019 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
7 ;;;
8 ;;; This file is part of 8sync.
9 ;;;
10 ;;; 8sync is free software: you can redistribute it and/or modify it
11 ;;; under the terms of the GNU Lesser General Public License as
12 ;;; published by the Free Software Foundation, either version 3 of the
13 ;;; License, or (at your option) any later version.
14 ;;;
15 ;;; 8sync is distributed in the hope that it will be useful,
16 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;;; GNU Lesser General Public License for more details.
19 ;;;
20 ;;; You should have received a copy of the GNU Lesser General Public
21 ;;; License along with 8sync.  If not, see <http://www.gnu.org/licenses/>.
22
23 (define-module (8s-client)
24   #:use-module (oop goops)
25   #:use-module (8sync)
26   #:use-module (8sync systems websocket client)
27
28   #:export (main))
29
30 (define %default-server "ws://localhost:1236")
31
32 (define-actor <sleeper> (<actor>)
33   ((*init* sleeper-loop))
34   (sleep-secs #:init-value 3 #:getter sleeper-sleep-secs))
35
36 (define (sleeper-loop actor message)
37   (while (actor-alive? actor)
38     (display "Zzzzzzzz....\n")
39     ;; Sleep for a bit
40     (8sleep (sleeper-sleep-secs actor))))
41
42 (define (main . args)
43   (let* ((hive (make-hive))
44          (sleeper (bootstrap-actor hive <sleeper>))
45          (websocket-id (bootstrap-actor hive <websocket>
46                                         #:url %default-server ;; toggle open with url/with message
47                                         #:on-close (lambda (ws)
48                                                      (format (current-error-port) "on-close: ~s\n" ws))
49                                         #:on-error (lambda (ws e)
50                                                      (format (current-error-port) "on-error: ~s:~s\n" ws e))
51                                         #:on-message (lambda (ws msg)
52                                                        (format (current-error-port) "on-message: ~s:~s\n" ws msg))
53                                         #:on-open (lambda (ws)
54                                                     (format (current-error-port) "on-open: ~s\n" ws)
55                                                     (websocket-send ws 'message "Hello, Web Socket!"))))
56          (websocket ((@@ (8sync actors) hive-resolve-local-actor) hive websocket-id)))
57     (if (.url websocket)
58         (run-hive hive '())
59         (run-hive hive (list (bootstrap-message hive websocket-id 'open %default-server))))))
60
61 (main (command-line))