Example
var server = newAsyncHttpServer() proc cb(req: Request) {.async.} = let (success, error) = await(verifyWebsocketRequest(req, "myfancyprotocol")) if not success: echo "WS negotiation failed: " & error await req.respond(Http400, "Websocket negotiation failed: " & error) req.client.close else: echo "New websocket customer arrived!" while true: try: var f = await req.client.readData(false) echo "(opcode: " & $f.opcode & ", data: " & $f.data.len & ")" if f.opcode == Opcode.Text: waitFor req.client.sendText("thanks for the data!", false) else: waitFor req.client.sendBinary(f.data, false) except: echo getCurrentExceptionMsg() break req.client.close() echo ".. socket went away."
Procs
proc verifyWebsocketRequest*(req: Request; protocol = ""): Future[ tuple[valid: bool, error: string]] {.async.}
-
Verifies the request is a websocket request:
- Supports protocol version 13 only
- Does not support extensions (yet)
- Will auto-negotiate a compatible protocol based on your protocol param
If all validations pass, will give you a tuple (true, ""). You can pass in a empty protocol param to not perform negotiation; this is the equivalent of accepting all protocols the client might request.
If the client does not send any protocols, but you have given one, the request will fail.
If validation FAILS, the response will be (false, human-readable failure reason).
After successful negotiation, you can immediately start sending/reading websocket frames.
Source