ByteArrayReaderWriter.java 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package de.tudarmstadt.informatik.hostage.io;
  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.util.List;
  8. import de.tudarmstadt.informatik.hostage.wrapper.ByteArray;
  9. /**
  10. * Handles the reading and writing of the socket in- and outputstream for byte arrays
  11. * @author Mihai Plasoianu
  12. */
  13. public class ByteArrayReaderWriter implements ReaderWriter<ByteArray> {
  14. private BufferedInputStream in;
  15. private BufferedOutputStream out;
  16. private int SLEEPTIME;
  17. /**
  18. * Constructor
  19. * @param in inputstream of socket
  20. * @param out outputstream of socket
  21. * @param SLEEPTIME time until timeout
  22. */
  23. public ByteArrayReaderWriter(InputStream in, OutputStream out, int SLEEPTIME) {
  24. this.in = new BufferedInputStream(in);
  25. this.out = new BufferedOutputStream(out);
  26. this.SLEEPTIME = SLEEPTIME;
  27. }
  28. public ByteArray read() throws IOException {
  29. int availableBytes;
  30. while((availableBytes = in.available()) <= 0) {
  31. try {
  32. Thread.sleep(SLEEPTIME);
  33. } catch (InterruptedException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. byte[] buffer = new byte[availableBytes];
  38. in.read(buffer);
  39. return new ByteArray(buffer);
  40. }
  41. public void write(List<ByteArray> message) throws IOException {
  42. for (ByteArray m : message) {
  43. out.write(m.get());
  44. out.flush();
  45. }
  46. }
  47. }