racket-dns-2012/simple-udp-service.rkt

83 lines
2.8 KiB
Racket

#lang racket/base
;; Simple imperative UDP server harness.
(require racket/match)
(require racket/udp)
(require "dump-bytes.rkt")
(provide (struct-out udp-packet)
event-handlers
start-udp-service)
;; A UdpPacket is a (udp-packet Bytes String Uint16), and represents
;; either a received UDP packet and the source of the packet, or a UDP
;; packet ready to be sent along with the address to which it should
;; be sent.
(struct udp-packet (body host port) #:prefab)
;; TODO: Should packet-classifier be permitted to examine (or possibly
;; even transform!) the ServerState?
;; A Handler is a ClassifiedPacket ServerState -> ListOf<ClassifiedPacket> ServerState.
(define-syntax event-handlers
(syntax-rules ()
((_ old-state-var (pattern body ...) ...)
(list (cons (match-lambda (pattern #t) (_ #f))
(lambda (v old-state-var)
(match v
(pattern body ...))))
...))))
;; Starts a generic request/reply UDP server on the given port.
(define (start-udp-service
port-number ;; Uint16
packet-classifier ;; UdpPacket -> ClassifiedPacket
event-handlers ;; ListOf<Pair<ClassifiedPacket -> Boolean, Handler>>
default-handler ;; Handler
initial-state ;; ServerState
#:packet-size-limit
[packet-size-limit 65536])
(define s (udp-open-socket #f #f)) ;; the server socket
(udp-bind! s #f port-number) ;; bind it to the port we were given
(set! event-handlers ;; TEMPORARY while I figure out I/O
(cons (cons udp-packet?
(lambda (p state)
(match-define (udp-packet body host port) p)
(printf "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~n~v~n" body)
(dump-bytes! body (bytes-length body))
(flush-output)
(udp-send-to s host port body)
(values '() state)))
event-handlers))
(define (dispatch-events events old-state)
(if (null? events)
(read-and-dispatch old-state)
(let ((classified-packet (car events)))
(define-values (new-events new-state)
(let search ((handlers event-handlers))
(cond
[(null? handlers) (default-handler classified-packet old-state)]
[((caar handlers) classified-packet) ((cdar handlers) classified-packet old-state)]
[else (search (cdr handlers))])))
(dispatch-events (append (cdr events) new-events) new-state))))
(define (read-and-dispatch old-state)
(define buffer (make-bytes packet-size-limit))
(define-values (packet-length source-hostname source-port)
(udp-receive! s buffer))
(define packet (subbytes buffer 0 packet-length))
(printf ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>~n~v~n" packet)
(dump-bytes! buffer packet-length)
(flush-output)
(define packet-and-source (udp-packet packet source-hostname source-port))
(define classified-packet (packet-classifier packet-and-source))
(dispatch-events (list classified-packet) old-state))
(read-and-dispatch initial-state))