tasyncssl.nim 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. discard """
  2. file: "tasyncssl.nim"
  3. cmd: "nim $target --hints:on --define:ssl $options $file"
  4. output: "500"
  5. """
  6. import asyncdispatch, asyncnet, net, strutils, os
  7. when defined(ssl):
  8. var msgCount = 0
  9. const
  10. swarmSize = 10
  11. messagesToSend = 50
  12. var clientCount = 0
  13. proc sendMessages(client: AsyncSocket) {.async.} =
  14. for i in 0 .. <messagesToSend:
  15. await send(client, "Message " & $i & "\c\L")
  16. proc launchSwarm(port: Port) {.async.} =
  17. for i in 0 .. <swarmSize:
  18. var sock = newAsyncSocket()
  19. var clientContext = newContext(verifyMode = CVerifyNone)
  20. clientContext.wrapSocket(sock)
  21. await connect(sock, "localhost", port)
  22. await sendMessages(sock)
  23. close(sock)
  24. proc readMessages(client: AsyncSocket) {.async.} =
  25. while true:
  26. var line = await recvLine(client)
  27. if line == "":
  28. close(client)
  29. inc(clientCount)
  30. break
  31. else:
  32. if line.startswith("Message "):
  33. inc(msgCount)
  34. else:
  35. doAssert false
  36. proc createServer(port: Port) {.async.} =
  37. let serverContext = newContext(verifyMode = CVerifyNone,
  38. certFile = "tests/testdata/mycert.pem",
  39. keyFile = "tests/testdata/mycert.pem")
  40. var server = newAsyncSocket()
  41. serverContext.wrapSocket(server)
  42. server.setSockOpt(OptReuseAddr, true)
  43. bindAddr(server, port)
  44. server.listen()
  45. while true:
  46. let client = await accept(server)
  47. serverContext.wrapConnectedSocket(client, handshakeAsServer)
  48. asyncCheck readMessages(client)
  49. asyncCheck createServer(Port(10335))
  50. asyncCheck launchSwarm(Port(10335))
  51. while true:
  52. poll()
  53. if clientCount == swarmSize: break
  54. assert msgCount == swarmSize * messagesToSend
  55. echo msgCount