t3075.nim 915 B

123456789101112131415161718192021222324252627282930
  1. import asyncnet, asyncdispatch, strtabs
  2. type
  3. WebSocketCallback = proc (client: WebSocket, message: WebSocketMessage) {.closure, gcsafe.}
  4. WebSocketRecvClosure = proc (ws: WebSocket): Future[string] {.gcsafe.}
  5. WebSocketMessage = ref object
  6. msg: string
  7. WebSocket = ref object
  8. socket: AsyncSocket
  9. header: StringTableRef
  10. onOpen: WebSocketCallback
  11. onMessage: WebSocketCallback
  12. onClose: WebSocketCallback
  13. proc recv(ws: WebSocket, p: WebSocketRecvClosure): Future[string] {.async.}=
  14. if not ws.socket.isClosed():
  15. result = await ws.p()
  16. if result == "":
  17. ws.socket.close()
  18. if ws.onClose != nil:
  19. ws.onClose(ws, nil)
  20. return result
  21. proc reсvSize(ws: WebSocket, size: int): Future[string] {.async.} =
  22. proc recvSizeClosure(ws: WebSocket): Future[string] {.async.} =
  23. return await ws.socket.recv(size)
  24. return await ws.recv(recvSizeClosure)