tnetdial.nim 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. discard """
  2. cmd: "nim c --threads:on $file"
  3. exitcode: 0
  4. output: "OK"
  5. """
  6. import os, net, nativesockets, asyncdispatch
  7. ## Test for net.dial
  8. const port = Port(28431)
  9. proc initIPv6Server(hostname: string, port: Port): AsyncFD =
  10. let fd = createNativeSocket(AF_INET6)
  11. setSockOptInt(fd, SOL_SOCKET, SO_REUSEADDR, 1)
  12. var aiList = getAddrInfo(hostname, port, AF_INET6)
  13. if bindAddr(fd, aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32:
  14. freeAddrInfo(aiList)
  15. raiseOSError(osLastError())
  16. freeAddrInfo(aiList)
  17. if listen(fd) != 0:
  18. raiseOSError(osLastError())
  19. setBlocking(fd, false)
  20. var serverFd = fd.AsyncFD
  21. register(serverFd)
  22. result = serverFd
  23. # Since net.dial is synchronous, we use main thread to setup server,
  24. # and dial to it from another thread.
  25. proc testThread() {.thread.} =
  26. let fd = net.dial("::1", port)
  27. var s = newString(5)
  28. doAssert fd.recv(addr s[0], 5) == 5
  29. if s == "Hello":
  30. echo "OK"
  31. fd.close()
  32. proc test() =
  33. let serverFd = initIPv6Server("::1", port)
  34. var t: Thread[void]
  35. createThread(t, testThread)
  36. var done = false
  37. serverFd.accept().callback = proc(fut: Future[AsyncFD]) =
  38. serverFd.closeSocket()
  39. if not fut.failed:
  40. let fd = fut.read()
  41. fd.send("Hello").callback = proc() =
  42. fd.closeSocket()
  43. done = true
  44. while not done:
  45. poll()
  46. joinThread(t)
  47. # this would cause #13132 `for i in 0..<10000: test()`
  48. test()