create a java server socket that waits for messages from client using Thread Pool

jeremy james :
@FXML
private TextArea textarea;
@FXML
private ImageView imagev;

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
    Serverth Server = new Serverth();
    Server.start();
}


class Serverth extends Thread {
    @Override
    public void run() {
        try {
            final int NUM_THREAD = 99;


            ServerSocket socket = new ServerSocket(8078);
            ExecutorService exec = Executors.newFixedThreadPool(NUM_THREAD);
            System.out.println("SERVER SOCKET CREATED");


            while (!isInterrupted()) {
                Socket in = socket.accept();
                Runnable r = new ThreadedHandler(in);
                exec.execute(r);

            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }
}

class ThreadedHandler implements Runnable {

    private Socket incoming;

    public ThreadedHandler(Socket in) {
        incoming = in;
    }

    public void run() {
        try {
            try {
                ObjectInputStream is=new ObjectInputStream(incoming.getInputStream());

                while(true) {
                    if (is.available() > 0) {
                        String line = is.readUTF();

                        textarea.appendText("\n" + "[" + new java.util.Date() + "] : " + line);

                        if (line.contains("inviato")) {
                            Object obj = is.readObject();
                            Email ema = (Email) obj;
                            try {
                                SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy-hh-mm-ss");
                                FileOutputStream fileOut = new FileOutputStream("src/Server/" + ((Email) obj).getDestinat() + "/" +  formatter.format(((Email) obj).getData()) + ".txt");
                                ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
                                objectOut.writeObject(ema);
                                objectOut.flush();
                                objectOut.close();
                                System.out.println("The Object  was succesfully written to a file");

                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }

                        }

                    }
                }
                } catch(IOException ex) {
                ex.printStackTrace();
            }

        } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
            try {
                incoming.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    }
}

Inside the run method (in Serveth class), I create a server socket and call exec.execute method. Inside the run method (in ThreadedHandler class), the server is waiting for messages from the client (in this specific case, it creates a new .txt file but it is not important). Everything works but causes excessive use of the CPU and lag!!!

Joni :

InputSteam.available method returns a value instantly, telling you no bytes are available to be read, so this code runs a very "hot" spin loop:

            while(true) {
                if (is.available() > 0) {
                    ...
                }
            }

The available method is rarely useful and often gives confusing results (see for example inputstream.available() is 0 always). I would suggest you get rid of the if statement altogether:

            while(true) {
                String line = is.readUTF();

                textarea.appendText("\n" + "[" + new java.util.Date() + "] : " + line);
                ...
            }

There's no way for this your code to exit the loop normally. You may want to add a mechanism for the client to disconnect from the server.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=361227&siteId=1