tasyncdial.nim 1.4 KB

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