tasyncdial.nim 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. discard """
  2. file: "tasyncdial.nim"
  3. output: '''
  4. OK AF_INET
  5. OK AF_INET6
  6. '''
  7. """
  8. import
  9. nativesockets, os, asyncdispatch
  10. proc setupServerSocket(hostname: string, port: Port, domain: Domain): AsyncFD =
  11. ## Creates a socket, binds it to the specified address, and starts listening for connecitons.
  12. ## Registers the descriptor with the dispatcher of the current thread
  13. ## Raises OSError in case of an error.
  14. let fd = newNativeSocket(domain)
  15. setSockOptInt(fd, SOL_SOCKET, SO_REUSEADDR, 1)
  16. var aiList = getAddrInfo(hostname, port, domain)
  17. if bindAddr(fd, aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32:
  18. freeAddrInfo(aiList)
  19. raiseOSError(osLastError())
  20. freeAddrInfo(aiList)
  21. if listen(fd) != 0:
  22. raiseOSError(osLastError())
  23. setBlocking(fd, false)
  24. result = fd.AsyncFD
  25. register(result)
  26. proc doTest(domain: static[Domain]) {.async.} =
  27. const
  28. testHost = when domain == Domain.AF_INET6: "::1" else: "127.0.0.1"
  29. testPort = Port(17384)
  30. let serverFd = setupServerSocket(testHost, testPort, domain)
  31. let acceptFut = serverFd.accept()
  32. let clientFdFut = dial(testHost, testPort)
  33. let serverClientFd = await acceptFut
  34. serverFd.closeSocket()
  35. let clientFd = await clientFdFut
  36. let recvFut = serverClientFd.recv(2)
  37. await clientFd.send("Hi")
  38. let msg = await recvFut
  39. serverClientFd.closeSocket()
  40. clientFd.closeSocket()
  41. if msg == "Hi":
  42. echo "OK ", domain
  43. waitFor(doTest(Domain.AF_INET))
  44. waitFor(doTest(Domain.AF_INET6))