Или подскажите как реорганизовать код. Как сделать правильно. Суть в том, что "сервер" будет получать string-и и необходимо минимальное графической сопровождение типа "работает\не работает"
З.ы мне показалось логичным обернуть вызов сервера в Platform.runlatter, но при таком раскладе приложение намертво ложиться на бочек и не желает отвечать
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();
}
}