nim-websock/examples/server.nim
Dmitriy Ryajov 3e1599d790
Fix partial frame handling and allow extensions to hijack the flow (#56)
* moving files around

* wip

* wip

* move tls example into server example

* add tls functionality

* rename

* rename

* fix tests

* move extension related files to own folder

* use trace instead of debug

* export extensions

* rework partial frame handling and closing

* rework status codes as distincts

* logging

* re-enable extensions processing for frames

* enable all test for non-tls server

* remove tlsserver

* remove offset to mask - don't think we need it

* pass sessions extensions when calling send/recv

* adding encode/decode extensions flow test

* move server/client setup to helpers

* proper frame order execution on decode

* fix tls tests
2021-06-11 14:04:09 -06:00

55 lines
1.5 KiB
Nim

import std/uri
import pkg/[chronos,
chronicles,
httputils]
import ../ws/ws
import ../tests/keys
proc handle(request: HttpRequest) {.async.} =
trace "Handling request:", uri = request.uri.path
let path = when defined tls: "/wss" else: "/ws"
if request.uri.path != path:
return
trace "Initiating web socket connection."
try:
let server = WSServer.new()
let ws = await server.handleRequest(request)
if ws.readyState != Open:
error "Failed to open websocket connection"
return
trace "Websocket handshake completed"
while ws.readyState != ReadyState.Closed:
let recvData = await ws.recv()
trace "Client Response: ", size = recvData.len, binary = ws.binary
await ws.send(recvData,
if ws.binary: Opcode.Binary else: Opcode.Text)
except WebSocketError as exc:
error "WebSocket error:", exception = exc.msg
when isMainModule:
proc main() {.async.} =
let
address = initTAddress("127.0.0.1:8888")
socketFlags = {ServerFlags.TcpNoDelay, ServerFlags.ReuseAddr}
server = when defined tls:
TlsHttpServer.create(
address = address,
handler = handle,
tlsPrivateKey = TLSPrivateKey.init(SecureKey),
tlsCertificate = TLSCertificate.init(SecureCert),
flags = socketFlags)
else:
HttpServer.create(address, handle, flags = socketFlags)
server.start()
trace "Server listening on ", data = $server.localAddress()
await server.join()
waitFor(main())