Source Edit

This module provides an implementation of the streams interface for sockets. It contains two separate implementations, a ReadSocketStream and a WriteSocketStream.

The ReadSocketStream only supports reading, peeking, and seeking. It reads into a buffer, so even by seeking backwards it will only read the same position a single time from the underlying socket. To clear the buffer and free the data read into it you can call resetStream, this will also reset the position back to 0 but won’t do anything to the underlying socket.

The WriteSocketStream allows both reading and writing, but it performs the reads on the internal buffer. So by writing to the buffer you can then read back what was written but without receiving anything from the socket. You can also set the position and overwrite parts of the buffer, and to send anything over the socket you need to call flush at which point you can’t write anything to the buffer before the point of the flush (but it can still be read). Again to empty the underlying buffer you need to call resetStream.

Examples

  1. import std/socketstreams
  2. var
  3. socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  4. stream = newReadSocketStream(socket)
  5. socket.sendTo("127.0.0.1", Port(12345), "SOME REQUEST")
  6. echo stream.readLine() # Will call `recv`
  7. stream.setPosition(0)
  8. echo stream.readLine() # Will return the read line from the buffer
  9. stream.resetStream() # Buffer is now empty, position is 0
  10. echo stream.readLine() # Will call `recv` again
  11. stream.close() # Closes the socket
  1. import std/socketstreams
  2. var socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  3. socket.connect("127.0.0.1", Port(12345))
  4. var sendStream = newWriteSocketStream(socket)
  5. sendStream.write "NOM"
  6. sendStream.setPosition(1)
  7. echo sendStream.peekStr(2) # OM
  8. sendStream.write "I"
  9. sendStream.setPosition(0)
  10. echo sendStream.readStr(3) # NIM
  11. echo sendStream.getPosition() # 3
  12. sendStream.flush() # This actually performs the writing to the socket
  13. sendStream.setPosition(1)
  14. sendStream.write "I" # Throws an error as we can't write into an already sent buffer

Imports

net, streams

Types

  1. ReadSocketStream = ref ReadSocketStreamObj

Source Edit

  1. ReadSocketStreamObj = object of StreamObj

Source Edit

  1. WriteSocketStream = ref WriteSocketStreamObj

Source Edit

  1. WriteSocketStreamObj = object of ReadSocketStreamObj

Source Edit

Procs

  1. proc newReadSocketStream(s: Socket): owned ReadSocketStream {....raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc newWriteSocketStream(s: Socket): owned WriteSocketStream {....raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc resetStream(s: ReadSocketStream) {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc resetStream(s: WriteSocketStream) {....raises: [], tags: [], forbids: [].}

Source Edit