tsocketstreams.nim 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. discard """
  2. matrix: "--mm:refc; --mm:orc"
  3. output: '''
  4. OM
  5. NIM
  6. 3
  7. NIM
  8. NIM
  9. Hello server!
  10. Hi there client!
  11. '''"""
  12. import std/socketstreams, net, streams
  13. block UDP:
  14. var recvSocket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  15. var recvStream = newReadSocketStream(recvSocket)
  16. recvSocket.bindAddr(Port(12345), "127.0.0.1")
  17. var sendSocket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  18. sendSocket.connect("127.0.0.1", Port(12345))
  19. var sendStream = newWriteSocketStream(sendSocket)
  20. sendStream.write "NOM\n"
  21. sendStream.setPosition(1)
  22. echo sendStream.peekStr(2)
  23. sendStream.write "I"
  24. sendStream.setPosition(0)
  25. echo sendStream.readStr(3)
  26. echo sendStream.getPosition()
  27. sendStream.flush()
  28. echo recvStream.readLine()
  29. recvStream.setPosition(0)
  30. echo recvStream.readLine()
  31. recvStream.close()
  32. block TCP:
  33. var server = newSocket()
  34. server.setSockOpt(OptReusePort, true)
  35. server.bindAddr(Port(12345))
  36. server.listen()
  37. var
  38. client = newSocket()
  39. clientRequestStream = newWriteSocketStream(client)
  40. clientResponseStream = newReadSocketStream(client)
  41. client.connect("127.0.0.1", Port(12345))
  42. clientRequestStream.writeLine("Hello server!")
  43. clientRequestStream.flush()
  44. var
  45. incoming: Socket
  46. address: string
  47. server.acceptAddr(incoming, address)
  48. var
  49. serverRequestStream = newReadSocketStream(incoming)
  50. serverResponseStream = newWriteSocketStream(incoming)
  51. echo serverRequestStream.readLine()
  52. serverResponseStream.writeLine("Hi there client!")
  53. serverResponseStream.flush()
  54. serverResponseStream.close()
  55. serverRequestStream.close()
  56. echo clientResponseStream.readLine()
  57. clientResponseStream.close()
  58. clientRequestStream.close()