tacceptcloserace.nim 992 B

12345678910111213141516171819202122232425262728293031323334353637
  1. discard """
  2. exitcode: 0
  3. output: ""
  4. """
  5. import asyncdispatch, net, os, nativesockets
  6. # bug: https://github.com/nim-lang/Nim/issues/5279
  7. proc setupServerSocket(hostname: string, port: Port): AsyncFD =
  8. let fd = createNativeSocket()
  9. if fd == osInvalidSocket:
  10. raiseOSError(osLastError())
  11. setSockOptInt(fd, SOL_SOCKET, SO_REUSEADDR, 1)
  12. var aiList = getAddrInfo(hostname, port)
  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. result = fd.AsyncFD
  21. register(result)
  22. const port = Port(5614)
  23. for i in 0..100:
  24. let serverFd = setupServerSocket("localhost", port)
  25. serverFd.accept().callback = proc(fut: Future[AsyncFD]) =
  26. if not fut.failed:
  27. fut.read().closeSocket()
  28. var fd = createAsyncNativeSocket()
  29. waitFor fd.connect("localhost", port)
  30. serverFd.closeSocket()
  31. fd.closeSocket()