tasyncnetudp.nim 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # It is a reproduction of the 'tnewasyncudp' test code, but using a high level
  2. # of asynchronous procedures. Output: "5000"
  3. import asyncdispatch, asyncnet, nativesockets, net, strutils
  4. var msgCount = 0
  5. var recvCount = 0
  6. const
  7. messagesToSend = 100
  8. swarmSize = 50
  9. serverPort = 10333
  10. var
  11. sendports = 0
  12. recvports = 0
  13. proc saveSendingPort(port: Port) =
  14. sendports = sendports + int(port)
  15. proc saveReceivedPort(port: Port) =
  16. recvports = recvports + int(port)
  17. proc launchSwarm(serverIp: string, serverPort: Port) {.async.} =
  18. var i = 0
  19. while i < swarmSize:
  20. var sock = newAsyncSocket(nativesockets.AF_INET, nativesockets.SOCK_DGRAM,
  21. Protocol.IPPROTO_UDP, false)
  22. bindAddr(sock, address = "127.0.0.1")
  23. let (null, localPort) = getLocalAddr(sock)
  24. var k = 0
  25. while k < messagesToSend:
  26. let message = "Message " & $(i * messagesToSend + k)
  27. await asyncnet.sendTo(sock, serverIp, serverPort, message)
  28. let (data, fromIp, fromPort) = await recvFrom(sock, 16384)
  29. if data == message:
  30. saveSendingPort(localPort)
  31. inc(recvCount)
  32. inc(k)
  33. close(sock)
  34. inc(i)
  35. proc readMessages(server: AsyncSocket) {.async.} =
  36. let maxResponses = (swarmSize * messagesToSend)
  37. var i = 0
  38. while i < maxResponses:
  39. let (data, fromIp, fromPort) = await recvFrom(server, 16384)
  40. if data.startsWith("Message ") and fromIp == "127.0.0.1":
  41. await sendTo(server, fromIp, fromPort, data)
  42. inc(msgCount)
  43. saveReceivedPort(fromPort)
  44. inc(i)
  45. proc createServer() {.async.} =
  46. var server = newAsyncSocket(nativesockets.AF_INET, nativesockets.SOCK_DGRAM, Protocol.IPPROTO_UDP, false)
  47. bindAddr(server, Port(serverPort), "127.0.0.1")
  48. asyncCheck readMessages(server)
  49. asyncCheck createServer()
  50. asyncCheck launchSwarm("127.0.0.1", Port(serverPort))
  51. while true:
  52. poll()
  53. if recvCount == swarmSize * messagesToSend:
  54. break
  55. doAssert msgCount == swarmSize * messagesToSend
  56. doAssert sendports == recvports
  57. echo msgCount