nim-websock/examples/server.nim
Dmitriy Ryajov 64da1a4344
Rework http (#38)
* wip

* wip

* move http under ws folder

* use asyctest

* wip

* wip

* rework response sending

* make example work with latest changes

* wip request/response

* misc

* fix example to use new http layer

* pass tls flags to client

* more cleanup

* unused imports

* more unsused imports

* better headers

* add helpre sendError

* export sendError

* attach selected proto to session

* move proto to session

* handle unsupported version

* fix tests

* comment out for now

* fix utf8 tests

* allow tests to be ran in tls

* misc

* use Port type

* add tls flags

* better api

* run tls tests

* fix tests on windows

* allow running tests with tls

* mic

* wip

* fix autobahn ci

* handle close

* cleanup

* logging and error handling

* remove old stream
2021-05-31 20:39:14 -06:00

47 lines
1.2 KiB
Nim

import std/uri
import pkg/[chronos,
chronicles,
httputils]
import ../ws/ws
proc handle(request: HttpRequest) {.async.} =
debug "Handling request:", uri = request.uri.path
if request.uri.path != "/ws":
return
debug "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
debug "Websocket handshake completed"
while true:
let recvData = await ws.recv()
if ws.readyState == ReadyState.Closed:
debug "Websocket closed"
break
debug "Client Response: ", size = recvData.len
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 = HttpServer.create(address, handle, flags = socketFlags)
server.start()
info "Server listening at ", data = $server.localAddress()
await server.join()
waitFor(main())