WebsocketWebSocket Protocol Support (RFC 6455)
This module provides functions for the WebSocket HTTP upgrade handshake. WebSocket connections are established by upgrading an HTTP/1.1 connection using the Upgrade mechanism.
(* Client: initiate WebSocket upgrade *)
let key = Websocket.generate_key () in
let headers = Websocket.make_upgrade_headers ~key () in
(* ... send request with these headers ... *)
(* Client: validate server response *)
match Websocket.validate_upgrade_response ~key ~status ~headers with
| Ok () -> (* Connection upgraded successfully *)
| Error reason -> (* Handshake failed *)generate_key () creates a random Sec-WebSocket-Key value.
Generates a cryptographically random 16-byte nonce and base64-encodes it. The result is suitable for use in the Sec-WebSocket-Key header.
compute_accept ~key computes the expected Sec-WebSocket-Accept value.
The computation is: base64(SHA-1(key + magic_guid))
validate_accept ~key ~accept validates a server's Sec-WebSocket-Accept.
parse_protocols s parses a Sec-WebSocket-Protocol header value.
Example: "graphql-ws, graphql-transport-ws" -> ["graphql-ws"; "graphql-transport-ws"]
protocols_to_string protocols formats protocols as a header value.
select_protocol ~offered ~supported selects a mutually acceptable protocol.
An extension with optional parameters.
Example: permessage-deflate; client_max_window_bits
val parse_extensions : string -> extension listparse_extensions s parses a Sec-WebSocket-Extensions header value.
Example: "permessage-deflate; client_max_window_bits"
val extensions_to_string : extension list -> stringextensions_to_string extensions formats extensions as a header value.
val has_extension : name:string -> extension list -> boolhas_extension ~name extensions checks if an extension is present.
val get_extension_params :
name:string ->
extension list ->
(string * string option) list optionget_extension_params ~name extensions gets parameters for an extension.
val make_upgrade_headers :
key:string ->
?protocols:string list ->
?extensions:extension list ->
?origin:string ->
unit ->
Headers.tmake_upgrade_headers ~key ?protocols ?extensions ?origin () builds headers for a WebSocket upgrade request.
Sets the following headers:
Upgrade: websocketConnection: UpgradeSec-WebSocket-Key: {key}Sec-WebSocket-Version: 13Sec-WebSocket-Protocol: ... (if protocols provided)Sec-WebSocket-Extensions: ... (if extensions provided)Origin: ... (if origin provided)val validate_upgrade_response :
key:string ->
status:int ->
headers:Headers.t ->
(unit, string) resultvalidate_upgrade_response ~key ~status ~headers validates a WebSocket upgrade response.
Checks that: