package network;
import file.*;
import java.net.*;
import java.util.Calendar;
import main.ui.NodeConsole;
import peer.Peer;
import util.*;
/**
* A Pulse , to let the other nodes know that we exist
*/
public class Pulse extends Thread {
//Handle to the on screen pulse display
NodeConsole pulseConsole = null;
private String myAddress = null;
private int broadcastSocket;
private boolean closeDown = false;
private static final int PULSE_DELTA = 3;
private int latency = 0;
public Pulse(String threadName, String pcAddress, int socket, int latency) {
super(threadName);
myAddress = pcAddress;
broadcastSocket = socket;
pulseConsole=new NodeConsole();
this.latency = latency;
}
public Pulse(int socket) {
super();
broadcastSocket = socket;
pulseConsole=new NodeConsole();
}
public void run() {
pulseConsole.start("Pulse Out","This shows all the Pulse Messages we send\n");
ping();
}
public void ping() {
try {
pulseConsole.log("Thread: " + this.getName() + " - Joining Multicast Socket Group");
InetAddress group = InetAddress.getByName("224.5.6.7");
MulticastSocket multiSocket = new MulticastSocket(6789);
pulseConsole.log("Thread: " + this.getName() + " - Joined Multicast Socket Group");
//Get required info
// String myAddress = InetAddress.getLocalHost().getHostAddress();
//new peer broadcast
Peer pulsePeer = new Peer(myAddress,latency,LocalFileOperation.getFileCount());
MessageConvertor messageConvert = new MessageConvertor();
byte[] peerAsByteArray = messageConvert.serializePeerPing(pulsePeer);
pulseConsole.log("Thread: " + this.getName() + " - Converted Peer ID Message");
//old stuff below
multiSocket.joinGroup(group);
pulseConsole.log("Thread: " + this.getName() + " - Getting datagram packet");
DatagramPacket hi = new DatagramPacket(peerAsByteArray,
peerAsByteArray.length, group, broadcastSocket);
int i = 0;
pulseConsole.log("Thread: " + this.getName() + " - Pulse.ping()");
while(!closeDown) {
//Update Peer with latest Time
pulsePeer.setLastRefresh(Calendar.getInstance().getTime());
//Reserialise
peerAsByteArray = messageConvert.serializePeerPing(pulsePeer);
hi = new DatagramPacket(peerAsByteArray,
peerAsByteArray.length, group, broadcastSocket);
// Yield to other threads - make app more responsive
Thread.yield();
// Need to construct the Peer object everytime we go through the loop
// or just get the dynamic data (latency, file list etc)
sleep(1000 * PULSE_DELTA);
multiSocket.send(hi);
pulseConsole.log("Thread: " + this.getName() + " : Pinging: " + ++i +" Details - Latency: "+pulsePeer.getLatency()+" NumberOfFiles: "+pulsePeer.getNumberOfFiles());
}
multiSocket.leaveGroup(group);
pulseConsole.log("Thread: " + this.getName() + " - Departed Multicast Socket Group");
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isCloseDown() {
return closeDown;
}
public void setCloseDown(boolean closeDown) {
this.closeDown = closeDown;
}
}