tasyncawait.nim 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import asyncdispatch, asyncnet, nativesockets, net, strutils
  2. from stdtest/netutils import bindAvailablePort
  3. var msgCount = 0
  4. const
  5. swarmSize = 40
  6. messagesToSend = 50
  7. var clientCount = 0
  8. proc sendMessages(client: AsyncFD) {.async.} =
  9. for i in 0 ..< messagesToSend:
  10. await send(client, "Message " & $i & "\c\L")
  11. proc launchSwarm(port: Port) {.async.} =
  12. for i in 0 ..< swarmSize:
  13. var sock = createAsyncNativeSocket()
  14. await connect(sock, "localhost", port)
  15. await sendMessages(sock)
  16. closeSocket(sock)
  17. proc readMessages(client: AsyncFD) {.async.} =
  18. # wrapping the AsyncFd into a AsyncSocket object
  19. var sockObj = newAsyncSocket(client)
  20. var (ipaddr, port) = sockObj.getPeerAddr()
  21. doAssert ipaddr == "127.0.0.1"
  22. (ipaddr, port) = sockObj.getLocalAddr()
  23. doAssert ipaddr == "127.0.0.1"
  24. while true:
  25. var line = await recvLine(sockObj)
  26. if line == "":
  27. closeSocket(client)
  28. clientCount.inc
  29. break
  30. else:
  31. if line.startsWith("Message "):
  32. msgCount.inc
  33. else:
  34. doAssert false
  35. proc createServer(server: AsyncFD) {.async.} =
  36. discard server.SocketHandle.listen()
  37. while true:
  38. asyncCheck readMessages(await accept(server))
  39. let server = createAsyncNativeSocket()
  40. let port = bindAvailablePort(server.SocketHandle)
  41. asyncCheck createServer(server)
  42. asyncCheck launchSwarm(port)
  43. while true:
  44. poll()
  45. if clientCount == swarmSize: break
  46. doAssert msgCount == swarmSize * messagesToSend
  47. doAssert msgCount == 2000