tasyncawait.nim 1.7 KB

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