0

I have two following classes (including only main methods for simplicity)

public class UDPServer {

    public static void main(String[] args) throws IOException {
        int serverPort = 9876;
        DatagramSocket socket = new DatagramSocket(serverPort);
        byte[] buffer = new byte[1024];
        boolean isConnected = true;
        while (isConnected) {
            try {
                DatagramPacket request = new DatagramPacket(buffer, buffer.length);
                socket.receive(request);
                DatagramPacket reply = new DatagramPacket(
                        request.getData(),
                        request.getLength(),
                        request.getAddress(),
                        request.getPort()
                        );
                socket.send(reply);
            } catch (IOException ex) {
                isConnected = false;
                Logger.getLogger(UDPServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}

public class UDPClient {

    public static void main(String[] args) {
        String pathToQuery = getUserInput();
        List<Packet> queried = UDPServer.getQueriedServerDataTypes(pathToQuery);
        try {
            if (args.length < 1) {
                System.out.println("Usage: UDPCLient <msg> <server host name>");
                System.exit(-1);
            }

            // Create a new datagram socket
            DatagramSocket socket = new DatagramSocket();

            // Preferred IPv4 address (cmd: ipconfig/all)
            InetAddress host = InetAddress.getByName(args[0]);
            int serverPort = 9876;

            for (int i = 0; i < queried.size(); i++) {
                Packet dataType = queried.get(i);
                String requestFile = "data_type_request_v" + (i + 1) + ".txt";
                UDPServer.saveToFile(
                        dataType,
                        "Server request.",
                        requestFile
                );

                // Serialize Packet object to an array of bytes
                byte[] data = Tools.serialize(dataType);
                System.out.println("Sent: " + Arrays.toString(data));

                // Request datagram packet will store data query for the server
                DatagramPacket request = new DatagramPacket(
                        Objects.requireNonNull(data),
                        data.length,
                        host,
                        serverPort
                );

                // Send serialized datagram packet to the server
                socket.send(request);

                // The reply datagram packet will store data returned by the server
                DatagramPacket reply = new DatagramPacket(data, data.length);
                System.out.println("Reply: " + Arrays.toString(reply.getData()));

                // Acquire data returned by the server
                socket.receive(reply);

                // Store deserialized data in null Packet object.
                Packet read = (Packet) Tools.deserialize(data);
                System.out.println("Reading deserialized data...\n" + read.toString());
                String responseFile = "data_type_response_v" + (i + 1) + ".txt";
                UDPServer.saveToFile(
                        read,
                        "Server response.",
                        responseFile
                );

                boolean isResponseEqualRequest = UDPServer.isResponseEqualRequest(
                        requestFile,
                        responseFile
                );

                if (isResponseEqualRequest) {
                    System.out.println("Communication successful. Server response corresponds to the request.");
                } else {
                    System.out.println("Communication unsuccessful. Server response does not correspond to the request.");
                }
            }

            // Close the datagram socket
            socket.close();

        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(UDPClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

In order for the UDPClient to work properly, UDPServer has to be running in the background. I want to run the UDPServer.main() in parallel thread and as soon as UDPClient.main() finishes, the thread should terminate as well.

How do I do that?

Filip Szczybura
  • 407
  • 5
  • 14
  • Have a look at the official tutorial: [Defining and Starting a Thread](https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html) – Lino Apr 14 '21 at 10:09
  • Unfortunately it does not help me at all. After I run the thread it does not stop even after using join() at the end of main in UDPClient – Filip Szczybura Apr 14 '21 at 10:39
  • See also this other question: [How to properly stop the Thread in Java?](https://stackoverflow.com/questions/10961714/how-to-properly-stop-the-thread-in-java). For you to stop a thread, you either need to interrupt it, or set a flag, indicating to stop the `while` loop – Lino Apr 14 '21 at 10:41
  • Unfortunately the flag does not stop the Server from working. – Filip Szczybura Apr 14 '21 at 11:38

0 Answers0