V
V
Vladislav Vinokurov2019-03-26 02:46:21
Java
Vladislav Vinokurov, 2019-03-26 02:46:21

Why doesn't form loading work when adding code to initialize?

Or tell me how to refactor the code. How to do it right. The bottom line is that the "server" will receive strings and a minimum graphical support of the "working \ not working"
type is required. wishes to answer

public class AppDesktop extends Application implements Initializable {

    public static void main(String[] args) {
        launch(args);
    }
    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("MainWin.fxml"));

        primaryStage.setTitle("Log share :)");
        primaryStage.setScene(new Scene(root, 900, 500));
        primaryStage.show();



    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {



        try {
            new Server();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

server
public class Server implements ConnectionListener{


    public static void main(String[] args) {

        try {
            new Server();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static final int PORT = 2454;
    List<Connection> connectionList = new ArrayList();


    public Server() throws IOException {


        ServerSocket serverSocket = new ServerSocket(PORT);

        while (true) {
            new Connection(this, serverSocket.accept());
        }
    }






    @Override
    public synchronized void onConnectionReady(Connection connection) {

        System.out.println("Подключен новый клиент " + connection.toString());
        connectionList.add(connection);

    }

    @Override
    public synchronized void newMessageOn(Connection connection, String message) {

        System.out.println(message);
        sendToAll(message);
        openWebpage(message);



    }

    public static boolean openWebpage(String link) {
        URI u = null;
        try {
            u = new URI(link);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
        if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
            try {
                desktop.browse(u);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }


    @Override
    public synchronized void connectionException(Connection connection, Exception exception) {

    }

    @Override
    public synchronized void onDisconnect(Connection connection) {

        connectionList.remove(connection);
        System.out.println("Client disconnected: " + connection);
    }


    private void sendToAll(String message) {
        connectionList.forEach((connection) -> connection.sendString(message));
    }


}

connection
public class Connection {


    private final Socket socket;
    private final ConnectionListener eventListener;
    private final BufferedReader in;
    private final BufferedWriter out;
    private Thread connectionThread;


    /**
     * Конструктор для подлючения клиентов
     * @param connectionListener
     * @param port порт подключения
     * @param ip_adress ip адресс подключения
     */
    public Connection(ConnectionListener connectionListener, String ip_adress, int port) throws IOException {

        this(connectionListener, new Socket(ip_adress, port));

    }

    /**
     * Конструктор серверной части
     * @param listener
     * @param socket
     */
    public Connection(ConnectionListener listener, Socket socket) throws IOException {

        this.socket = socket;
        eventListener = listener;

        in = new BufferedReader(new InputStreamReader(socket.getInputStream(), Charset.forName("UTF-8")));
        out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8")));


         connectionThread = new Thread(() -> {

             try {

                 eventListener.onConnectionReady(Connection.this);

                 while (!connectionThread.isInterrupted()) {

                     eventListener.newMessageOn(Connection.this, in.readLine());

                 }
             } catch (IOException e) {
                 eventListener.connectionException(Connection.this, e);
             } catch (Exception e) {
                 e.printStackTrace();
             } finally {
                 eventListener.onDisconnect(Connection.this);
             }
         });

         connectionThread.start();
    }


    public synchronized void sendString(String value) {

        try {

            out.write(value + "\r\n");

            out.flush();

        } catch (IOException e) {

            eventListener.connectionException(this, e);

            disconnect();

        }

    }

    public synchronized void disconnect() {

        connectionThread.interrupt();

        try {
            socket.close();
        } catch (IOException e) {
            eventListener.connectionException(this, e);
        }

    }


    @Override
    public String toString() {
        return "Connection: " + socket.getInetAddress() + ": " + socket.getPort();
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Vinokurov, 2019-03-26
@KDoV

While explaining about the platforms, the runlater understood everything himself - it's not a rather lightweight task to use the runlater and wrap everything in a Service :) It turns out that when you write about a problem, you think better!
This works great:

Service<Void> service = new Service<Void>() {
            @Override
            protected Task<Void> createTask() {
                return new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {
                     

                        try {
                            new Server();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                };
            }
        };
        service.start();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question