nim-websock/examples/server.nim

47 lines
1.2 KiB
Nim
Raw Normal View History

import std/uri
import pkg/[chronos,
chronicles,
httputils]
WIP: Implement websocket TLS. (#7) * Update http to use chronos http. * Implement TLS in websocket. * Add webscoket TLS test. * Minor nit. * Add TLS test file. * Update http to use chronos http. (#6) * Update http to use chronos http. * Add stream.nim file. * Address comments. * Fix CI failure. * Minor change. * Address comments. * Fix windows CI failing test. * minor cleanup * spacess * more idiomatic connect * use stew/base10 Co-authored-by: Dmitriy Ryajov <dryajov@gmail.com> * Implement TLS in websocket. * Minor nit. * merge master * wip * Update http to use chronos http. (#6) * Update http to use chronos http. * Add stream.nim file. * Address comments. * Fix CI failure. * Minor change. * Address comments. * Fix windows CI failing test. * minor cleanup * spacess * more idiomatic connect * use stew/base10 Co-authored-by: Dmitriy Ryajov <dryajov@gmail.com> * Update http to use chronos http. * Implement TLS in websocket. * Minor nit. * Update http to use chronos http. (#6) * Update http to use chronos http. * Add stream.nim file. * Address comments. * Fix CI failure. * Minor change. * Address comments. * Fix windows CI failing test. * minor cleanup * spacess * more idiomatic connect * use stew/base10 Co-authored-by: Dmitriy Ryajov <dryajov@gmail.com> * Implement TLS in websocket. * Minor nit. * add testing keys * wip * fix test * wip * remove eth dep and add skipdirs * fix package structure * fix deps * check nim version * Fix CI failure. * Don't call `ws.stream.closeWait()` * always close both ends to complete the sequence * misc * don't fail on close * Fix windows CI. * fix linux x86 builds * use consistent connect pattern * move keys to better place * return dumbResponse * small cleanup Co-authored-by: Dmitriy Ryajov <dryajov@gmail.com>
2021-04-13 22:05:58 +00:00
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())