0

I will be accepting input from a socket into a string buffer, one byte at a time. I want to only process the contents of the string buffer when no input has been received for a certain period of time. Is there some library or way to do this that doesn't involve creating a new thread to track the time after every byte of input?

agjones
  • 11
  • 1
  • 1

1 Answers1

1

Yes. You can use the select mechanism to wait for new input, providing a timeout to limit how long you will wait. If the timeout expires before input arrives, you know no input has arrived during that time, and can then go do your processing. In java, see SocketChannel and Selector classes at: https://docs.oracle.com/javase/10/docs/api/java/nio/channels/package-summary.html. (Many tutorials and examples can be found around the web.)

You can also set a receive timeout on the underlying socket as explained here: https://stackoverflow.com/a/9150513/1076479

Given that you intend to only process your input when the channel is quiescent, why would you only receive input one byte at a time? Wouldn't it make sense to receive all available input in one fell swoop? That would be more efficient, and you can still use the above mechanisms to limit the time you wait for input.

Gil Hamilton
  • 11,973
  • 28
  • 51
  • Interesting, thank you. I think this implementation is more work than my use case requires- I will definitely be using this as my project becomes more complex. – agjones Apr 03 '18 at 17:20