3 WebSocket
(require net/websocket) |
The net/websocket library provides utilities to run and communicate with WebSocket servers, as specified in the WebSocket protocol IETF draft as of August 16th, 2010.
This module provides the exports from net/websocket/client and net/websocket/server.
3.1 Client API
(require net/websocket/client) |
procedure
(ws-connect u [#:headers headers]) → open-ws-conn?
u : ws-url? headers : (listof header?) = empty
This module also provides the exports from net/websocket/conn.
3.2 Server API
(require net/websocket/server) |
procedure
(ws-serve conn-handle [ #:conn-headers conn-headers #:tcp@ tcp@ #:port port #:listen-ip listen-ip #:max-waiting max-waiting #:timeout timeout #:confirmation-channel confirm-ch]) → (-> void) conn-handle : (open-ws-conn? any/c . -> . void)
conn-headers : (bytes? (listof header?) . -> . (values (listof header?) any/c)) = (λ (b hs) (values empty (void))) tcp@ : (unit/c (import) (export tcp^)) = raw:tcp@ port : tcp-listen-port? = 80 listen-ip : (or/c string? false/c) = #f max-waiting : integer? = 4 timeout : integer? = (* 60 60) confirm-ch : (or/c false/c async-channel?) = #f
All other arguments are used as in a Dispatching Server.
The #:tcp@ keyword is provided for building an SSL server.
This module also provides the exports from net/websocket/conn.
3.3 Connections
(require net/websocket/conn) |
WebSocket connection are synchronizable events.
parameter
(framing-mode) → (symbols 'old 'new)
(framing-mode mode) → void? mode : (symbols 'old 'new)
procedure
(open-ws-conn? x) → boolean?
x : any/c
procedure
(ws-conn-line ws) → bytes?
ws : ws-conn?
procedure
(ws-conn-closed? ws) → boolean?
ws : ws-conn?
procedure
(ws-conn-headers ws) → (listof header?)
ws : ws-conn?
WebSocket connection support only blocking calls:
procedure
ws : open-ws-conn? s : string?
procedure
(ws-recv ws) → (or/c string? eof-object?)
ws : open-ws-conn?
procedure
ws : open-ws-conn?
3.4 Example
This is a WebSocket echo server compatible with the browser origin security model:
(ws-serve #:port 8080 (λ (wsc _) (let loop () (define m (ws-recv wsc)) (printf "~a\n" m) (unless (eof-object? m) (ws-send! wsc m) (loop)))) #:conn-headers (λ (_ hs) (define origin (header-value (headers-assq* #"Origin" hs))) (values (list (make-header #"Sec-WebSocket-Origin" origin) (make-header #"Sec-WebSocket-Location" #"ws://localhost:8080/")) #f)))