如何将同一控制器的更多实例关联到一个Stage

时间:2018-01-04 12:15:59

标签: sockets client

我在处理邮件应用程序的服务器端时遇到问题。 我希望有更多的ServerController写在同一个TextArea上。 这些ServerController应该是具有不同字段值(ID,套接字和列表)的不同实例。

这是我的错误代码:

服务器加载UI并在不同的线程上运行MultiThreadHandler

public class Server extends Application {
        @Override
        public void start(Stage stage) throws Exception {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLServer.fxml"));
            stage.setTitle("Mail Server");
            stage.setScene(new Scene((Pane) loader.load()));

            ServerController controller = loader.<ServerController>getController();
            MultiThreadHandler handler = new MultiThreadHandler(controller);
            new Thread(handler).start();
            stage.show();
        }

        public static void main(String[] args) {
            launch(args);
        }

    }

每当客户端请求连接时,MultithreadHandler都会创建一个ServerController线程

public class MultiThreadHandler implements Runnable{

    private final ServerController controller;

    public MultiThreadHandler(ServerController controller){
        this.controller = controller;
    }
    @Override
    public void run() {
        try{
            ServerSocket UI = new ServerSocket(8189);
            while(true){
                Socket UserInterface = UI.accept();
                controller.setSocketUI(UserInterface);
                new Thread(controller).start();
            }
        } catch(IOException e){
            System.err.println(e.getMessage());
        }
    }

}

ServerSocket应该处理单个客户端。每个实例都应该有自己的ID,这是一个地址,它自己的Socket,用于与单个UI进行通信,以及它自己的列表,因为每个客户端都有它的邮件列表。相关部分代码标有**。

public class ServerController implements Runnable {

    private final String path = "C:\\Users\\Federico\\Desktop\\MVC-MAIL\\MVC-MAIL\\MVC-MAIL\\src\\server\\";
    @FXML
    private TextArea srv;

    @FXML
    public void initialize() {
        srv.setStyle("-fx-background-color:black;"
                + " -fx-control-inner-background:red;"
                + " -fx-font-family: Consolas; -fx-highlight-fill: #00ff00;"
                + " -fx-highlight-text-fill: #000000; "
                + " -fx-text-fill: #00ff00; ");
    }

    **private Socket socketUI;
    private String ID;**
    private transient ArrayList<Email> lista = null;

    **public void setSocketUI(Socket socketUI) {
        this.socketUI = socketUI;
    }**



    public void initSocket() throws Exception {
        try {
            srv.setText(srv.getText() + "\n" + "Waiting for client...");
            srv.setText(srv.getText() + "\n" + "accepted");
            try {
                **ObjectInputStream in = new ObjectInputStream(socketUI.getInputStream());
                ObjectOutputStream out = new ObjectOutputStream(socketUI.getOutputStream());**
                try {
                    srv.setText(srv.getText() + "\n" + "reading mail ID...");
                    **ID = (String) in.readObject();//from client**
                    srv.setText(srv.getText() + "\n" + "ID: " + ID);
                } catch (ClassNotFoundException ex) {
                    srv.setText(srv.getText() + "\n" + ex.getMessage());
                }
                srv.setText(srv.getText() + "\n" + "reading text file...");
                **lista = readCSV(ID);**
                srv.setText(srv.getText() + " DONE");
                srv.setText(srv.getText() + "\n" + "writing email-list to client...");
                out.writeObject(lista);
                srv.setText(srv.getText() + " DONE");
                while (true) {
                    try {
                        Object oggetto;
                        oggetto = in.readObject();
                        Class classe = oggetto.getClass();
                        int intero = 0;
                        if (classe.isInstance(intero)) {    //Elimina mail
                            srv.setText(srv.getText() + "\n" + "Deleting email...");
                            int index = (int) oggetto;
                            lista = readCSV(ID);
                            lista.remove(index);
                            writeCSV(lista, ID);
                            srv.setText(srv.getText() + " DONE");
                        } else if (classe.isInstance(new ArrayList<>())) { //nuova mail
                            ArrayList<Email> incoming = (ArrayList<Email>) oggetto;
                            for (Email elem : incoming) {
                                String destinatario = elem.getDestinatario();
                                System.out.println("dest: " + destinatario);
                                File f = new File(path + destinatario + ".txt");
                                if (f.exists()) {
                                    ArrayList<Email> casellaDest = readCSV(destinatario);
                                    casellaDest.add(elem);
                                    writeCSV(casellaDest, destinatario);
                                    out.writeObject(true);
                                } else {
                                    out.writeObject(false);
                                }
                            }
                        } else if (classe.isInstance(true)) {
                            lista = readCSV(ID);
                            out.writeObject(lista);
                            System.err.println(ID + " --> " + socketUI.getLocalAddress());
                        }
                    } catch (ClassNotFoundException ex) {
                        srv.setText(srv.getText() + "\n" + ex.getMessage());
                    }

                }
            } finally {
                socketUI.close();
            }
        } catch (IOException e) {
            srv.setText(srv.getText() + "\n" + e.getMessage());
        }

    }

    private ArrayList<Email> readCSV(String address) {
        // file esiste già?
        ArrayList<Email> list = new ArrayList<>();
        String csvFile = path + address + ".txt";
        BufferedReader br = null;
        String line;
        try {
            br = new BufferedReader(new FileReader(csvFile));
            while ((line = br.readLine()) != null) {
                if (!"".equals(line)) {
                    String[] riga = line.split("§ ");
                    String[] data = riga[4].split("-");
                    int anno = Integer.parseInt(data[0]);
                    int mese = Integer.parseInt(data[1]);
                    int giorno = Integer.parseInt(data[2]);
                    list.add(new Email(riga[0], riga[1], riga[2], riga[3], LocalDate.of(anno, mese, giorno)));
                } else {
                }
            }
        } catch (IOException ex) {
            System.err.println(ex.getStackTrace()[0].getLineNumber());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    srv.setText(srv.getText() + "\n" + e.getMessage());
                }
            }
        }
        return list;
    }

    private void writeCSV(ArrayList<Email> lista, String address) {
        BufferedWriter bw = null;
        String CSV = path + address + ".txt";
        try {
            bw = new BufferedWriter(new FileWriter(CSV));
            for (Email mail : lista) {
                String mittente = mail.getMittente() + "§ ";
                String destinatario = mail.getDestinatario() + "§ ";
                String titolo = mail.getTitolo() + "§ ";
                String testo = mail.getTesto() + "§ ";
                LocalDate data = mail.getData();
                String riga = mittente + destinatario + titolo + testo + data;
                bw.write(riga);
                bw.newLine();
            }
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        } finally {
            if (bw != null) {
                try {
                    bw.flush();
                    bw.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }

    @Override
    public void run() {
        try {
            initSocket();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

}

0 个答案:

没有答案