2021-04-14 11:07:38 +00:00
|
|
|
import pkg/[chronos,
|
2021-04-05 21:01:10 +00:00
|
|
|
chronos/apps/http/httpserver,
|
|
|
|
chronicles,
|
2021-04-14 11:07:38 +00:00
|
|
|
httputils]
|
2021-04-13 22:05:58 +00:00
|
|
|
|
|
|
|
import ../ws/ws
|
2021-03-11 03:34:14 +00:00
|
|
|
|
2021-04-05 21:01:10 +00:00
|
|
|
proc process(r: RequestFence): Future[HttpResponseRef] {.async.} =
|
|
|
|
if r.isOk():
|
|
|
|
let request = r.get()
|
|
|
|
debug "Handling request:", uri = request.uri.path
|
|
|
|
if request.uri.path == "/ws":
|
|
|
|
debug "Initiating web socket connection."
|
|
|
|
try:
|
2021-04-14 11:07:38 +00:00
|
|
|
let ws = await createServer(request, "")
|
2021-04-05 21:01:10 +00:00
|
|
|
if ws.readyState != Open:
|
|
|
|
error "Failed to open websocket connection."
|
|
|
|
return
|
2021-05-22 08:26:45 +00:00
|
|
|
|
2021-04-05 21:01:10 +00:00
|
|
|
debug "Websocket handshake completed."
|
2021-04-14 11:07:38 +00:00
|
|
|
while true:
|
2021-05-22 09:04:40 +00:00
|
|
|
let recvData = await ws.recv()
|
2021-04-14 11:07:38 +00:00
|
|
|
if ws.readyState == ReadyState.Closed:
|
|
|
|
debug "Websocket closed."
|
2021-04-05 21:01:10 +00:00
|
|
|
break
|
2021-05-22 09:04:40 +00:00
|
|
|
|
2021-04-05 21:01:10 +00:00
|
|
|
debug "Client Response: ", size = recvData.len
|
2021-05-22 09:04:40 +00:00
|
|
|
await ws.send(recvData,
|
|
|
|
if ws.binary: Opcode.Binary else: Opcode.Text)
|
2021-04-13 22:05:58 +00:00
|
|
|
|
2021-04-05 21:01:10 +00:00
|
|
|
except WebSocketError as exc:
|
|
|
|
error "WebSocket error:", exception = exc.msg
|
2021-05-21 09:53:17 +00:00
|
|
|
|
2021-04-05 21:01:10 +00:00
|
|
|
discard await request.respond(Http200, "Hello World")
|
|
|
|
else:
|
|
|
|
return dumbResponse()
|
2021-03-11 03:34:14 +00:00
|
|
|
|
|
|
|
when isMainModule:
|
2021-04-05 21:01:10 +00:00
|
|
|
let address = initTAddress("127.0.0.1:8888")
|
|
|
|
let socketFlags = {ServerFlags.TcpNoDelay, ServerFlags.ReuseAddr}
|
|
|
|
let res = HttpServerRef.new(
|
|
|
|
address, process,
|
|
|
|
socketFlags = socketFlags)
|
2021-04-13 22:05:58 +00:00
|
|
|
|
2021-04-05 21:01:10 +00:00
|
|
|
let server = res.get()
|
|
|
|
server.start()
|
|
|
|
info "Server listening at ", data = address
|
2021-04-13 22:05:58 +00:00
|
|
|
waitFor server.join()
|