package network;
import peer.*;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Calendar;
import main.ui.NodeConsole;
import util.*;
public class PulseMonitor extends Thread {
//Handle to the on screen pulse display
NodeConsole pulseMonitorConsole = null;
private int broadcastSocket;
private boolean closeDown = false;
private PeerGroup peerGroup = null;
public PulseMonitor(String threadName, int socket, PeerGroup theGroup) {
super(threadName);
broadcastSocket = socket;
peerGroup = theGroup;
pulseMonitorConsole = new NodeConsole();
}
public PulseMonitor(int socket, PeerGroup theGroup) {
broadcastSocket = socket;
peerGroup = theGroup;
pulseMonitorConsole = new NodeConsole();
}
public void run() {
pulseMonitorConsole.start("Pulse In","This shows Pulses we receive from other nodes");
monitor();
}
public void monitor() {
//locar vars
pulseMonitorConsole.log("Thread:" + this.getName() + " - Starting");
MessageConvertor messageConvert = new MessageConvertor();
try {
pulseMonitorConsole.log("Thread: " + this.getName() + " - Joining Multicast Socket Group");
MulticastSocket multiSocket = new MulticastSocket(broadcastSocket);
InetAddress group = InetAddress.getByName("224.5.6.7");
multiSocket.joinGroup(group);
pulseMonitorConsole.log("Thread: " + this.getName() + " - Joined Multicast Socket Group");
DatagramPacket packet;
// for (int i = 0; i < 5; i++) {
while(!closeDown) {
//Yield to other threads - make app more responsive
Thread.yield();
byte[] buf = new byte[100000]; //TODO : This will only work of no files < 10.
packet = new DatagramPacket(buf, buf.length);
multiSocket.receive(packet);
//Convert the buffer to a byte array of the correct length
byte[] correctBuf = new byte[packet.getLength()];
for(int a=0; a<correctBuf.length;a++){
//TODO optimize this
correctBuf[a]=buf[a];
}
//Now convert this back to peer object
Peer pulseIn = messageConvert.deserialisePeerPing(correctBuf);
pulseMonitorConsole.log("Thread:" + this.getName() + " - " + "Received Pulse from HostName: "+pulseIn.getHostName());
pulseMonitorConsole.log("Thread:" + this.getName() + " - " + "Received Pulse number of files: " + pulseIn.getNumberOfFiles());
pulseMonitorConsole.log("Thread: " + this.getName() + "- " + "Received Pulse - Latency: "+pulseIn.getLatency());
//Update with our local time - avoids differences in clocks between nodes
pulseIn.setLastRefresh(Calendar.getInstance().getTime());
//String received = new String(packet.getData());
//String[] data = received.split(",");
//int numFiles = new Integer(data[1]).intValue();
peerGroup.notifyOccurred(pulseIn, pulseMonitorConsole);
}
multiSocket.leaveGroup(group);
pulseMonitorConsole.log("Thread: " + this.getName() + " - Departed Multicast Socket Group");
multiSocket.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public boolean isCloseDown() {
return closeDown;
}
public void setCloseDown(boolean closeDown) {
this.closeDown = closeDown;
}
}