2021-06-01 02:39:14 +00:00
|
|
|
|
|
|
|
import std/uri
|
2021-04-14 11:07:38 +00:00
|
|
|
import pkg/[chronos,
|
2021-04-05 21:01:10 +00:00
|
|
|
chronicles,
|
2021-04-14 11:07:38 +00:00
|
|
|
httputils]
|
2021-04-13 22:05:58 +00:00
|
|
|
|
2021-05-25 22:39:10 +00:00
|
|
|
import ../ws/ws
|
2021-03-11 03:34:14 +00:00
|
|
|
|
2021-06-01 02:39:14 +00:00
|
|
|
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
|
2021-03-11 03:34:14 +00:00
|
|
|
|
|
|
|
when isMainModule:
|
2021-06-01 02:39:14 +00:00
|
|
|
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())
|