I'm implementing a program where the controller(server) calls the agent(client) periodically and sends it IP address.
Controller.java
public class Controller { static int discoveryInterval; NetworkDiscovery n1; Controller(){ discoveryInterval=6000; } public static void main(String[] args) throws IOException { Timer t1=new Timer(); t1.schedule(new NetworkDiscovery(), discoveryInterval); } } NetworkDiscovery.java-
import java.io.*; public class NetworkDiscovery extends TimerTask { protected DatagramSocket socket = null; protected BufferedReader in = null; public NetworkDiscovery() throws IOException { this("NetworkDiscovery"); } public NetworkDiscovery(String name) throws IOException { super(name); socket = new DatagramSocket(4445); } public void run() { try { byte[] buf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // figure out response String dString = InetAddress.getLocalHost().toString(); buf = dString.getBytes(); // send the response to the client at "address" and "port" InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); } catch (IOException e) { e.printStackTrace(); } socket.close(); } } On the Agent(client's side)- Agent.java
public class Agent { ackDiscovery ackDisc=new ackDiscovery(); public static void main(String[] args) throws SocketException,UnknownHostException,IOException { ackDiscovery ackDisc=new ackDiscovery(); ackDisc.ackInfo(); } } And ackDiscovery.java-
public class ackDiscovery { int agentListenPort; void ackDiscovery(){ agentListenPort=4455; } public void ackInfo() throws SocketException, UnknownHostException, IOException{ // get a datagram socket DatagramSocket socket = new DatagramSocket(); // send request byte[] buf = new byte[256]; InetAddress address = InetAddress.getByName(MY_IP); DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); // get response packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // display response String received = new String(packet.getData()); System.out.println("Data received:"+ received); socket.close(); } } When I run the Controller(Server), the Agent's(client's) side get executed only once though the Controller is still listening. Also, if I re-run the agent, nothing happens. Can someone please help me?