Example
import websocket, asynchttpserver, asyncnet, asyncdispatch var server = newAsyncHttpServer() proc cb(req: Request) {.async.} = let (ws, error) = await(verifyWebsocketRequest(req, "myfancyprotocol")) if ws.isNil: 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 ws.readData() echo "(opcode: ", f.opcode, ", data: ", f.data.len, ")" if f.opcode == Opcode.Text: waitFor ws.sendText("thanks for the data!", masked = false) else: waitFor ws.sendBinary(f.data, masked = false) except: echo getCurrentExceptionMsg() break ws.close() echo ".. socket went away." waitfor server.serve(Port(8080), cb)
Procs
proc verifyWebsocketRequest(req: Request; protocol = ""): Future[ tuple[ws: AsyncWebSocket, error: string]] {.
raises: [FutureError], tags: [RootEffect].}-
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 (AsyncWebSocket, ""). 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 (nil, human-readable failure reason).
After successful negotiation, you can immediately start sending/reading websocket frames.