racket-matrix-2012/os2-tcp-test-bytewise-echo.rkt

48 lines
1.4 KiB
Racket

#lang racket/base
;; A more different trivial example program demonstrating os2-tcp.rkt.
(require racket/string)
(require racket/set)
(require racket/match)
(require "os2.rkt")
(require "os2-timer.rkt")
(require "os2-tcp.rkt")
(define ((connection-handler local-addr remote-addr) self-pid)
(define (reader-role)
(role (topic-subscriber (tcp-channel remote-addr local-addr (wild)))
[(tcp-channel remote _ (? bytes? bs))
(list (send-tcp-credit remote-addr local-addr 16)
(send-message (tcp-channel local-addr remote-addr bs)))]
[(tcp-channel remote _ (? eof-object?))
(kill)]))
(transition 'no-state
(send-tcp-credit remote-addr local-addr 16)
(reader-role)))
(define (listener local-addr)
(transition 'no-state
(role (topic-subscriber (tcp-channel (wild) local-addr (wild)) #:monitor? #t)
#:topic t
#:on-presence (match t
[(topic 'publisher (tcp-channel remote-addr (== local-addr) _) #f)
(spawn (connection-handler local-addr remote-addr))]))))
(define (main port)
(define (arm-timer)
(role (topic-subscriber (timer-expired (wild) (wild)))
#:name 'waiter
#:on-presence (send-message (set-timer 'label 500 'relative))
[(timer-expired _ _) (list (delete-role 'waiter)
(arm-timer))]))
(ground-vm
(transition 'none
(spawn tcp-spy)
(spawn tcp-driver)
(spawn timer-driver)
(arm-timer)
(spawn (listener (tcp-listener port))))))
(main 5999)