tsocketstreams.nim 1.6 KB

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