Advertisement
Guest User

CLIENT

a guest
Jan 24th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. package rs.ac.bg.etf.kdp.sanja.net;
  2.  
  3. import java.io.*;
  4. import java.net.Socket;
  5.  
  6. import rs.ac.bg.etf.kdp.sanja.interfaces.*;
  7.  
  8. public class RemoteMessageBox<T> implements MessageBox<T> {
  9.  
  10. String host;
  11. int port;
  12.  
  13. public RemoteMessageBox(String host, int port) {
  14. super();
  15. this.host = host;
  16. this.port = port;
  17. }
  18.  
  19. @Override
  20. public void send(Message<T> msg, Priority priority, long ttl) {
  21. int count = 0;
  22. int maxTries = 3;
  23. boolean flag = true;
  24.  
  25. while (flag == true) {
  26. try (Socket socket = new Socket(host, port);
  27. ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
  28. ObjectInputStream in = new ObjectInputStream(socket.getInputStream());) {
  29. try {
  30. out.writeObject("send");
  31. out.writeObject(msg);
  32. out.writeObject(priority);
  33. out.writeLong(ttl);
  34. out.flush();
  35. in.readObject();
  36. flag = false;
  37. } catch (IOException e) {
  38. if (++count == maxTries) {
  39. flag = false;
  40. e.printStackTrace();
  41. }
  42. }
  43. } catch (Exception e) {
  44. if (++count == maxTries) {
  45. flag = false;
  46. e.printStackTrace();
  47. }
  48. }
  49. }
  50. }
  51.  
  52. @SuppressWarnings("unchecked")
  53. @Override
  54. public Message<T> receive(long ttd, Status status) {
  55. int count = 0;
  56. int maxTries = 3;
  57. boolean flag = true;
  58. Message<T> msg = null;
  59.  
  60. while (flag == true) {
  61. try (Socket socket = new Socket(host, port);
  62. ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
  63. ObjectInputStream in = new ObjectInputStream(socket.getInputStream());) {
  64. try {
  65. out.writeObject("receive");
  66. msg = (Message<T>) in.readObject();
  67. out.writeObject("OK");
  68. flag = false;
  69. } catch (IOException e) {
  70. if (++count == maxTries) {
  71. flag = false;
  72. e.printStackTrace();
  73. }
  74. }
  75. } catch (Exception e) {
  76. if (++count == maxTries) {
  77. flag = false;
  78. e.printStackTrace();
  79. }
  80. }
  81. }
  82. return msg;
  83. }
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement