tasyncssl.nim 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. discard """
  2. cmd: "nim $target --hints:on --define:ssl $options $file"
  3. disabled: osx
  4. """
  5. import asyncdispatch, asyncnet, net, strutils
  6. import stdtest/testutils
  7. when defined(ssl):
  8. var port0: Port
  9. var msgCount = 0
  10. const
  11. swarmSize = 10
  12. messagesToSend = 50
  13. var clientCount = 0
  14. proc sendMessages(client: AsyncSocket) {.async.} =
  15. for i in 0 ..< messagesToSend:
  16. await send(client, "Message " & $i & "\c\L")
  17. proc launchSwarm(port: Port) {.async.} =
  18. for i in 0 ..< swarmSize:
  19. var sock = newAsyncSocket()
  20. var clientContext = newContext(verifyMode = CVerifyNone)
  21. clientContext.wrapSocket(sock)
  22. await connect(sock, "localhost", port)
  23. await sendMessages(sock)
  24. close(sock)
  25. proc readMessages(client: AsyncSocket) {.async.} =
  26. while true:
  27. var line = await recvLine(client)
  28. if line == "":
  29. close(client)
  30. inc(clientCount)
  31. break
  32. else:
  33. if line.startsWith("Message "):
  34. inc(msgCount)
  35. else:
  36. doAssert false
  37. proc createServer() {.async.} =
  38. let serverContext = newContext(verifyMode = CVerifyNone,
  39. certFile = "tests/testdata/mycert.pem",
  40. keyFile = "tests/testdata/mycert.pem")
  41. var server = newAsyncSocket()
  42. serverContext.wrapSocket(server)
  43. server.setSockOpt(OptReuseAddr, true)
  44. bindAddr(server)
  45. port0 = getLocalAddr(server)[1]
  46. server.listen()
  47. while true:
  48. let client = await accept(server)
  49. serverContext.wrapConnectedSocket(client, handshakeAsServer)
  50. asyncCheck readMessages(client)
  51. asyncCheck createServer()
  52. asyncCheck launchSwarm(port0)
  53. while true:
  54. poll()
  55. if clientCount == swarmSize: break
  56. template cond(): bool = msgCount == swarmSize * messagesToSend
  57. when defined(windows):
  58. # currently: msgCount == 0
  59. flakyAssert cond()
  60. elif defined(linux) and int.sizeof == 8:
  61. # currently: msgCount == 10
  62. flakyAssert cond()
  63. doAssert msgCount > 0
  64. else: doAssert cond(), $msgCount