package client;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;


/**
 * Stores byte arrays sent from client/server
 * @author julian
 *
 */
public class ByteMonitor {
	private LinkedList<byte[]> fromServer;
	private LinkedList<byte[]> toServer;
	private Socket socket;
	private String ipport;
	
	
	public ByteMonitor(String ipport){
		fromServer = new LinkedList<byte[]>();
		toServer = new LinkedList<byte[]>();
		this.ipport = ipport;
	}
	
	public boolean initConnection(){
		int split = ipport.indexOf(':');
		String ip = ipport.substring(0, split);
		int port = Integer.parseInt(ipport.substring(split+1));
		try {
			socket = new Socket(ip, port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return socket.isConnected();
		
	}
	
	
	/**
	 * Messages sent from server are put here.
	 * @param msg
	 */
	public synchronized void putArrayFromServer(byte[] msg){
		fromServer.add(msg);
		notifyAll();
	}
	
	/**
	 * Messages sent from server are read here.
	 * @return
	 */
	public synchronized byte[] readArrayFromServer(){
		while(fromServer.isEmpty()){
			try{
				wait();
			} catch (InterruptedException e){
				e.printStackTrace();
			}
		}
		byte[] tmp = fromServer.poll();
		notifyAll();
		return tmp;
	}
	
	

	/**
	 * Messages sent from client are put here.
	 * @param msg
	 */
	public synchronized void putArrayToServer(byte[] msg){
		toServer.add(msg);
		notifyAll();
	}
	
	/**
	 * Messages sent from client are read here.
	 * @return
	 */
	public synchronized byte[] readArrayToServer(){
		while(toServer.isEmpty()){
			try{
				wait();
			} catch (InterruptedException e){
				e.printStackTrace();
			}
		}
		byte[] tmp = toServer.poll();
		notifyAll();
		return tmp;
	}

}

@@ -362,16 +362,59 @@
 ort;%0A%09%0A%09
+/**%0A%09 * Init monitor%0A%09 * @param ipport%0A%09 */
 %0A%09public
@@ -551,16 +551,77 @@
 t;%0A%09%7D%0A%09%0A
+%09/**%0A%09 * Init connection to server.%0A%09 * @return success%0A%09 */%0A
 %09public 
@@ -975,11 +975,8 @@
 ();%0A
-%09%09%0A
 %09%7D%0A%09
@@ -1925,11 +1925,10 @@
 tmp;%0A%09%7D%0A
-%0A
 %7D%0A

add comments