ByteArrayReaderWriter.java 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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.Packet;
  9. /**
  10. * Handles the reading and writing of the socket in- and outputstream for byte arrays
  11. * @author Mihai Plasoianu
  12. * @author Wulf Pfeiffer
  13. */
  14. public class ByteArrayReaderWriter implements ReaderWriter {
  15. private BufferedInputStream in;
  16. private BufferedOutputStream out;
  17. private int SLEEPTIME;
  18. /**
  19. * Constructor
  20. * @param in inputstream of socket
  21. * @param out outputstream of socket
  22. * @param SLEEPTIME time until timeout
  23. */
  24. public ByteArrayReaderWriter(InputStream in, OutputStream out, int SLEEPTIME) {
  25. this.in = new BufferedInputStream(in);
  26. this.out = new BufferedOutputStream(out);
  27. this.SLEEPTIME = SLEEPTIME;
  28. }
  29. public Packet read() throws IOException {
  30. int availableBytes;
  31. while((availableBytes = in.available()) <= 0) {
  32. try {
  33. Thread.sleep(SLEEPTIME);
  34. } catch (InterruptedException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. byte[] buffer = new byte[availableBytes];
  39. in.read(buffer);
  40. return new Packet(buffer);
  41. }
  42. public void write(List<Packet> outputLine) throws IOException {
  43. for (Packet o : outputLine) {
  44. out.write(o.getMessage());
  45. out.flush();
  46. }
  47. }
  48. }