Note that there are some explanatory texts on larger screens.

plurals
  1. POServer Client Program in Java
    text
    copied!<p>I'm implementing a program where the controller(server) calls the agent(client) periodically and sends it IP address. </p> <p>Controller.java</p> <pre><code>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); } } </code></pre> <p>NetworkDiscovery.java- </p> <pre><code>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(); } } </code></pre> <p>On the Agent(client's side)- Agent.java</p> <pre><code>public class Agent { ackDiscovery ackDisc=new ackDiscovery(); public static void main(String[] args) throws SocketException,UnknownHostException,IOException { ackDiscovery ackDisc=new ackDiscovery(); ackDisc.ackInfo(); } } </code></pre> <p>And ackDiscovery.java-</p> <pre><code>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(); } } </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload