rsc3/sosc/ip.rkt

76 lines
1.4 KiB
Racket
Raw Normal View History

2014-02-15 19:03:37 +00:00
#lang racket
(require "bytevector.rkt")
2014-02-15 19:03:37 +00:00
(provide (all-defined-out))
;; data udp
(struct udp* (s h p))
;; any -> bool
(define udp:socket?
udp*?)
;; string -> int -> socket
(define udp:open
(lambda (h p)
(udp* (udp-open-socket h p) h p)))
2014-02-15 19:03:37 +00:00
;; socket -> bytevector -> ()
(define udp:send
(lambda (u b)
(let ((s (udp*-s u))
(h (udp*-h u))
(p (udp*-p u)))
(udp-send-to* s h p b))))
2014-02-15 19:03:37 +00:00
;; socket -> maybe bytevector
(define udp:recv
(lambda (u)
(let* ((s (udp*-s u))
(h (udp*-h u))
(p (udp*-p u))
(b (make-bytes 8192))
(r (sync/timeout 1.0 (udp-receive!-evt s b))))
2014-02-15 19:03:37 +00:00
(if r
(subbytes b 0 (car r))
#f))))
2014-02-15 19:03:37 +00:00
;; socket -> ()
(define udp:close
(lambda (u)
(udp-close (udp*-s u))))
2014-02-15 19:03:37 +00:00
;; data tcp
(define-struct tcp* (i o h p))
2014-02-15 19:03:37 +00:00
;; any -> bool
(define tcp:socket?
tcp*?)
;; string -> int -> socket
(define tcp:open
(lambda (h p)
(let-values
(((i o) (tcp-connect h p)))
(file-stream-buffer-mode i 'none)
(file-stream-buffer-mode o 'none)
(make-tcp* i o h p))))
2014-02-15 19:03:37 +00:00
;; socket -> bytevector -> ()
(define tcp:send
(lambda (fd b)
(let ((o (tcp*-o fd)))
(put-bytevector o b))))
;; socket -> int -> maybe bytevector
(define tcp:read
(lambda (fd n)
(get-bytevector-n (tcp*-i fd) n)))
;; socket -> ()
(define tcp:close
(lambda (fd)
(close-input-port (tcp*-i fd))
2014-02-15 23:48:21 +00:00
(close-output-port (tcp*-o fd))))