Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package rs.ac.bg.etf.kdp.sanja.net;
- import java.io.*;
- import java.net.Socket;
- import rs.ac.bg.etf.kdp.sanja.interfaces.*;
- public class RemoteMessageBox<T> implements MessageBox<T> {
- String host;
- int port;
- public RemoteMessageBox(String host, int port) {
- super();
- this.host = host;
- this.port = port;
- }
- @Override
- public void send(Message<T> msg, Priority priority, long ttl) {
- int count = 0;
- int maxTries = 3;
- boolean flag = true;
- while (flag == true) {
- try (Socket socket = new Socket(host, port);
- ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
- ObjectInputStream in = new ObjectInputStream(socket.getInputStream());) {
- try {
- out.writeObject("send");
- out.writeObject(msg);
- out.writeObject(priority);
- out.writeLong(ttl);
- out.flush();
- in.readObject();
- flag = false;
- } catch (IOException e) {
- if (++count == maxTries) {
- flag = false;
- e.printStackTrace();
- }
- }
- } catch (Exception e) {
- if (++count == maxTries) {
- flag = false;
- e.printStackTrace();
- }
- }
- }
- }
- @SuppressWarnings("unchecked")
- @Override
- public Message<T> receive(long ttd, Status status) {
- int count = 0;
- int maxTries = 3;
- boolean flag = true;
- Message<T> msg = null;
- while (flag == true) {
- try (Socket socket = new Socket(host, port);
- ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
- ObjectInputStream in = new ObjectInputStream(socket.getInputStream());) {
- try {
- out.writeObject("receive");
- msg = (Message<T>) in.readObject();
- out.writeObject("OK");
- flag = false;
- } catch (IOException e) {
- if (++count == maxTries) {
- flag = false;
- e.printStackTrace();
- }
- }
- } catch (Exception e) {
- if (++count == maxTries) {
- flag = false;
- e.printStackTrace();
- }
- }
- }
- return msg;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement