tasyncssl.nim 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. discard """
  2. cmd: "nim $target --hints:on --define:ssl $options $file"
  3. """
  4. import asyncdispatch, asyncnet, net, strutils
  5. import stdtest/testutils
  6. when defined(ssl):
  7. var port0: Port
  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() {.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)
  44. port0 = getLocalAddr(server)[1]
  45. server.listen()
  46. while true:
  47. let client = await accept(server)
  48. serverContext.wrapConnectedSocket(client, handshakeAsServer)
  49. asyncCheck readMessages(client)
  50. asyncCheck createServer()
  51. asyncCheck launchSwarm(port0)
  52. while true:
  53. poll()
  54. if clientCount == swarmSize: break
  55. template cond(): bool = msgCount == swarmSize * messagesToSend
  56. when defined(windows):
  57. # currently: msgCount == 0
  58. flakyAssert cond()
  59. elif defined(linux) and int.sizeof == 8:
  60. # currently: msgCount == 10
  61. flakyAssert cond()
  62. doAssert msgCount > 0
  63. else: doAssert cond(), $msgCount