diff --git a/.idea/artifacts/AphorismsClient.xml b/.idea/artifacts/AphorismsClient.xml new file mode 100644 index 0000000..e33e41f --- /dev/null +++ b/.idea/artifacts/AphorismsClient.xml @@ -0,0 +1,12 @@ + + + $PROJECT_DIR$/out/artifacts/AphorismsClient + + + + + + + + + \ No newline at end of file diff --git a/.idea/artifacts/AphorismsServer.xml b/.idea/artifacts/AphorismsServer.xml new file mode 100644 index 0000000..52cc0e0 --- /dev/null +++ b/.idea/artifacts/AphorismsServer.xml @@ -0,0 +1,12 @@ + + + $PROJECT_DIR$/out/artifacts/AphorismsServer + + + + + + + + + \ No newline at end of file diff --git a/.idea/artifacts/ControlerElectricClock.xml b/.idea/artifacts/ControlerElectricClock.xml new file mode 100644 index 0000000..8e55980 --- /dev/null +++ b/.idea/artifacts/ControlerElectricClock.xml @@ -0,0 +1,11 @@ + + + $PROJECT_DIR$/out/artifacts/ControlerElectricClock + + + + + + + + \ No newline at end of file diff --git a/.idea/artifacts/ExchangeClient.xml b/.idea/artifacts/ExchangeClient.xml new file mode 100644 index 0000000..ac83c0b --- /dev/null +++ b/.idea/artifacts/ExchangeClient.xml @@ -0,0 +1,14 @@ + + + $PROJECT_DIR$/out/artifacts/ExchangeClient + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/artifacts/MessenferClient.xml b/.idea/artifacts/MessenferClient.xml new file mode 100644 index 0000000..bc203c1 --- /dev/null +++ b/.idea/artifacts/MessenferClient.xml @@ -0,0 +1,13 @@ + + + $PROJECT_DIR$/out/artifacts/MessenferClient + + + + + + + + + + \ No newline at end of file diff --git a/.idea/artifacts/MessengerServer.xml b/.idea/artifacts/MessengerServer.xml new file mode 100644 index 0000000..f27a75d --- /dev/null +++ b/.idea/artifacts/MessengerServer.xml @@ -0,0 +1,13 @@ + + + $PROJECT_DIR$/out/artifacts/MessengerServer + + + + + + + + + + \ No newline at end of file diff --git a/.idea/artifacts/ServerElectricClock.xml b/.idea/artifacts/ServerElectricClock.xml new file mode 100644 index 0000000..f5f1a13 --- /dev/null +++ b/.idea/artifacts/ServerElectricClock.xml @@ -0,0 +1,11 @@ + + + $PROJECT_DIR$/out/artifacts/ServerElectricClock + + + + + + + + \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index dff5f3a..0000000 --- a/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: java diff --git a/Java-lab-6.iml b/Java-lab-6.iml new file mode 100644 index 0000000..d677c18 --- /dev/null +++ b/Java-lab-6.iml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/out/artifacts/AphorismsClient/AphorismsClient.jar b/out/artifacts/AphorismsClient/AphorismsClient.jar new file mode 100644 index 0000000..306505e Binary files /dev/null and b/out/artifacts/AphorismsClient/AphorismsClient.jar differ diff --git a/out/artifacts/AphorismsServer/AphorismsServer.jar b/out/artifacts/AphorismsServer/AphorismsServer.jar new file mode 100644 index 0000000..b2883ce Binary files /dev/null and b/out/artifacts/AphorismsServer/AphorismsServer.jar differ diff --git a/out/artifacts/ControlerElectricClock/ControlerElectricClock.jar b/out/artifacts/ControlerElectricClock/ControlerElectricClock.jar new file mode 100644 index 0000000..938784f Binary files /dev/null and b/out/artifacts/ControlerElectricClock/ControlerElectricClock.jar differ diff --git a/out/artifacts/ControllerAphorisms/ControllerAphorisms.jar b/out/artifacts/ControllerAphorisms/ControllerAphorisms.jar new file mode 100644 index 0000000..85e66d7 Binary files /dev/null and b/out/artifacts/ControllerAphorisms/ControllerAphorisms.jar differ diff --git a/out/artifacts/ExchangeClient/Java-lab-6.jar b/out/artifacts/ExchangeClient/Java-lab-6.jar new file mode 100644 index 0000000..aea10c6 Binary files /dev/null and b/out/artifacts/ExchangeClient/Java-lab-6.jar differ diff --git a/out/artifacts/MessenferClient/MessenferClient.jar b/out/artifacts/MessenferClient/MessenferClient.jar new file mode 100644 index 0000000..b266e28 Binary files /dev/null and b/out/artifacts/MessenferClient/MessenferClient.jar differ diff --git a/out/artifacts/MessengerServer/MessengerServer.jar b/out/artifacts/MessengerServer/MessengerServer.jar new file mode 100644 index 0000000..4243810 Binary files /dev/null and b/out/artifacts/MessengerServer/MessengerServer.jar differ diff --git a/out/artifacts/ServerElectricClock/ServerElectricClock.jar b/out/artifacts/ServerElectricClock/ServerElectricClock.jar new file mode 100644 index 0000000..afa6123 Binary files /dev/null and b/out/artifacts/ServerElectricClock/ServerElectricClock.jar differ diff --git a/resourses/Balaton.jpg b/resourses/Balaton.jpg new file mode 100644 index 0000000..d467c6e Binary files /dev/null and b/resourses/Balaton.jpg differ diff --git a/resourses/Messeges.json b/resourses/Messeges.json new file mode 100644 index 0000000..3144740 --- /dev/null +++ b/resourses/Messeges.json @@ -0,0 +1,55 @@ +[ + { + "id": "111", + "time": "05:59", + "mes": "Natasha, do you sleep? It`s your cats!" + }, + { + "id": "111", + "time": "06:00", + "mes": "Natasha, wake up! It`s 6 o`clock now!" + }, + { + "id": "111", + "time": "06:01", + "mes": "Natasha, we have dropped everything!" + }, + { + "id": "111", + "time": "06:02", + "mes": "Natasha, we really have dropped everything!", + "isLast": true + }, + { + "id": "222", + "time": "12:24", + "mes": "Hey, stop watching cat video on youtube! Let`s do something useful!" + }, + { + "id": "222", + "time": "12:25", + "mes": "So, do you start write your code?" + }, + { + "id": "222", + "time": "12:26", + "mes": "Continue to work!" + }, + { + "id": "222", + "time": "23:00", + "mes": "Not bad! It`s enough for today, you can go to bed!", + "isLast": true + }, + { + "id": "333", + "time": "17:58", + "mes": "It`s time to check your mail!" + }, + { + "id": "333", + "time": "18:05", + "mes": "It`s time to go home...", + "isLast": true + } +] \ No newline at end of file diff --git a/resourses/Nietzsche.txt b/resourses/Nietzsche.txt new file mode 100644 index 0000000..a7cea54 --- /dev/null +++ b/resourses/Nietzsche.txt @@ -0,0 +1,20 @@ +"Если вы решили действовать — закройте двери для сомнений." Ф.Ницше +"Человек есть нечто, что до́лжно превзойти." Ф.Ницше +"Счастье человека зависит от его мыслей." Ф.Ницше +"Наш долг — это право, которое другие имеют на нас." Ф.Ницше +"Много говорить о себе – тоже способ себя скрывать." Ф.Ницше +"Если у человека есть зачем, он вынесет любое как." Ф.Ницше +"Не то, что ты обманул меня, а то, что я больше не могу верить тебе, потрясло меня." Ф.Ницше +"Чем больше человек молчит, тем больше он начинает говорить разумно." Ф.Ницше +"Без музыки жизнь была бы заблуждением." Ф.Ницше +"Я даю себя обманывать, чтобы не остерегаться обманщиков." Ф.Ницше +"Хороший брак покоится на таланте к дружбе." Ф.Ницше +"Невозможно быть свободным от того, от чего убегаешь." Ф.Ницше +"Я пришел помочь вам, а вы жалуетесь, что я не хочу плакать с вами." Ф.Ницше +"Где нельзя уже любить, там нужно — пройти мимо!" Ф.Ницше +"Красота — это обещание счастья." Ф.Ницше +"Иногда люди не хотят слышать правду, потому что они не хотят, чтобы их иллюзии были разрушены." Ф.Ницше +"Величайшие события — это не нашисамые шумные, а наши самые тихие часы." Ф.Ницше +"Кто не может повелевать себе, должен повиноваться." Ф.Ницше +"Даже у Бога есть свой ад — это любовь его к людям." Ф.Ницше +"Ни один победитель не верит в случайность." Ф.Ницше \ No newline at end of file diff --git a/src/ExchangeClient/Balaton.jpg b/src/ExchangeClient/Balaton.jpg new file mode 100644 index 0000000..d467c6e Binary files /dev/null and b/src/ExchangeClient/Balaton.jpg differ diff --git a/src/ExchangeClient/Controller.java b/src/ExchangeClient/Controller.java new file mode 100644 index 0000000..e6b8c25 --- /dev/null +++ b/src/ExchangeClient/Controller.java @@ -0,0 +1,81 @@ +package ExchangeClient; + +import javafx.application.Platform; +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.control.Button; +import javafx.scene.control.Label; +import javafx.scene.control.TextField; +import javafx.scene.image.ImageView; + +import java.io.IOException; +import java.net.URL; +import java.util.*; + +; + +public class Controller implements Initializable { + ExchangeClient exchangeClient = new ExchangeClient(); + + @FXML + private Button show; + @FXML + private Button off; + @FXML + private Label display; + @FXML + private TextField field; + @FXML + private ImageView picture; + + @Override + public void initialize(URL location, ResourceBundle resources) { + System.out.println("Controllers is initialiaezed!"); + display.setWrapText(true); + } + + @FXML + private void clickShow () throws IOException { + Timer t1 = new Timer(); + t1.schedule(new ExchangeClientTimerTask() { + @Override + public void run() { + System.out.println("ExchangeClientTimerTask is started" + new Date()); + try { + exchangeClient.contactToServer(); + ArrayList exchangeRates = exchangeClient.getExchangeRates(); + for (int i = 0; i display.setText(toSet)); + Thread.sleep(2500); + } + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + } + }, 0); + + } + + class ExchangeClientTimerTask extends TimerTask { + @Override + public void run() { + System.out.println("ExchangeClientTimerTask is started" + new Date()); + completeTask(); + System.out.println("ExchangeClientTimerTask is finished" + new Date()); + + } + private void completeTask() { + try { + Thread.sleep(0); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + @FXML + private void clickOff() throws IOException { + display.setText("I hope you like it! Bye!"); + } +} diff --git a/src/ExchangeClient/ExchangeClient.java b/src/ExchangeClient/ExchangeClient.java new file mode 100644 index 0000000..24ea66d --- /dev/null +++ b/src/ExchangeClient/ExchangeClient.java @@ -0,0 +1,64 @@ +package ExchangeClient; + +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.nodes.Element; +import org.jsoup.select.Elements; + +import java.io.IOException; +import java.net.NoRouteToHostException; +import java.net.URL; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; + +public class ExchangeClient { + private static String CURRENCY_INFO_URL = "https://cbr.ru/currency_base/daily/"; + private ArrayList currency = new ArrayList<>( + Arrays.asList(new String[]{"EUR", "CZK", "BYN", "USD", "GBP", "CHF", "TRY", "PLN"})); + private URL url; + private ArrayList exchangeRates = new ArrayList<>(); + + public void contactToServer () throws IOException { + try { + System.out.println("The client is started!"); + url = new java.net.URL(CURRENCY_INFO_URL); + Document html = Jsoup.parse(url, 5000); + Elements rows = html.body().getElementsByTag("tr"); + for (Element el : rows) { + if (currency.contains(el.child(1).text())) { + exchangeRates.add(el); + } + } + } catch (UnknownHostException e) { + System.out.println("The host isn`t found!"); + } catch (NoRouteToHostException e) { + System.out.println("The server isn`t available!"); + } catch (IOException e) { + System.out.println("The connection request is rejected!"); + } + System.out.println("The client is disconnected!"); + } + + public ArrayList getExchangeRates() { + ArrayList exchRates = new ArrayList<>(); + for (int i = 0; i + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Manifest/META-INF/MANIFEST.MF b/src/Manifest/META-INF/MANIFEST.MF new file mode 100644 index 0000000..91721b6 --- /dev/null +++ b/src/Manifest/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: electricClock.ServerElectricClock + diff --git a/src/Manifest1/META-INF/MANIFEST.MF b/src/Manifest1/META-INF/MANIFEST.MF new file mode 100644 index 0000000..1b7ea7b --- /dev/null +++ b/src/Manifest1/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: electricClock.Main + diff --git a/src/Manifest2/META-INF/MANIFEST.MF b/src/Manifest2/META-INF/MANIFEST.MF new file mode 100644 index 0000000..e42d6e0 --- /dev/null +++ b/src/Manifest2/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: aphorisms.AphorismsServer + diff --git a/src/Manifest3/META-INF/MANIFEST.MF b/src/Manifest3/META-INF/MANIFEST.MF new file mode 100644 index 0000000..b08190a --- /dev/null +++ b/src/Manifest3/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: aphorisms.AphorismsMain + diff --git a/src/Manifest4/META-INF/MANIFEST.MF b/src/Manifest4/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5701699 --- /dev/null +++ b/src/Manifest4/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: messenger.MessengerServer + diff --git a/src/Manifest5/META-INF/MANIFEST.MF b/src/Manifest5/META-INF/MANIFEST.MF new file mode 100644 index 0000000..c40cfdf --- /dev/null +++ b/src/Manifest5/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: messenger.messengerMain + diff --git a/src/Manifest6/META-INF/MANIFEST.MF b/src/Manifest6/META-INF/MANIFEST.MF new file mode 100644 index 0000000..81508bf --- /dev/null +++ b/src/Manifest6/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: ExchangeClient.Main + diff --git a/src/aphorisms/AphorismClient.java b/src/aphorisms/AphorismClient.java new file mode 100644 index 0000000..38828b8 --- /dev/null +++ b/src/aphorisms/AphorismClient.java @@ -0,0 +1,47 @@ +package aphorisms; + +import java.io.*; +import java.net.NoRouteToHostException; +import java.net.Socket; +import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; + +public class AphorismClient { + private Socket clientSocket; + private BufferedReader reader; + private BufferedReader incomingMessage; + private BufferedWriter outcomingMessage; + private String aphorism; + + + public void contactToServer () throws IOException { + try { + System.out.println("The client is started!"); + clientSocket = new Socket("localhost", 3333); + outcomingMessage = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); + outcomingMessage.write("Hi, server!\n"); + outcomingMessage.flush(); + incomingMessage = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8)); + aphorism = incomingMessage.readLine(); + System.out.println("We received " + aphorism); + } catch (UnknownHostException e) { + System.out.println("The host isn`t found!"); + } catch (NoRouteToHostException e) { + System.out.println("The server isn`t available!"); + } catch (IOException e) { + System.out.println("The connection request is rejected!"); + } + incomingMessage.close(); + clientSocket.close(); + System.out.println("The client is disconnected!"); + } + + public String getAphorism() { + return aphorism; + } + + public static void main(String[] args) throws IOException { + AphorismClient aphorismClient = new AphorismClient(); + aphorismClient.contactToServer(); + } +} diff --git a/src/aphorisms/AphorismsMain.java b/src/aphorisms/AphorismsMain.java new file mode 100644 index 0000000..380cf5c --- /dev/null +++ b/src/aphorisms/AphorismsMain.java @@ -0,0 +1,26 @@ +package aphorisms; + +import javafx.application.Application; +import javafx.stage.Stage; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; + +import java.io.IOException; + + +public class AphorismsMain extends Application { + + public static void main(String[] args) { + launch(args); + } + + @Override + public void start(Stage primaryStage) throws IOException { + Parent root = FXMLLoader.load(getClass().getResource("aphorisms.fxml")); + primaryStage.setTitle("Aphorisms"); + primaryStage.setScene(new Scene(root)); + primaryStage.setResizable(false); + primaryStage.show(); + } +} diff --git a/src/aphorisms/AphorismsServer.java b/src/aphorisms/AphorismsServer.java new file mode 100644 index 0000000..27d037e --- /dev/null +++ b/src/aphorisms/AphorismsServer.java @@ -0,0 +1,84 @@ +package aphorisms; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; + + +public class AphorismsServer extends Thread { + private Socket socket; + private PrintWriter outgoingMessage; + private BufferedReader incommingMessage; + static private List aphorismsN = new ArrayList<>(); + + public AphorismsServer(Socket socket) throws IOException { + this.socket = socket; + incommingMessage = new BufferedReader(new InputStreamReader(socket.getInputStream())); + outgoingMessage = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); + start(); + } + + static private List readAphorismFile() { + try { + BufferedReader bf = new BufferedReader( + new InputStreamReader( + ClassLoader.getSystemClassLoader().getResourceAsStream("Nietzsche.txt"))); + String line; + while ((line = bf.readLine()) != null) { + aphorismsN.add(line); + } + } catch (Exception ex) { + System.out.println(ex.getMessage()); + ex.printStackTrace(); + } + return aphorismsN; + } + + public void run() { + try { + while (true) { + System.out.println("Waiting for incomming Meassage..."); + String string = incommingMessage.readLine(); + System.out.println(string); + if (string != null && !string.equals("OFF")) { + int randomI = (int) (Math.random() * 19); + System.out.println("Send to client: " + aphorismsN.get(randomI)); + outgoingMessage.write(aphorismsN.get(randomI)); + outgoingMessage.write("\n"); + outgoingMessage.flush(); + } else { + System.out.println("Connection is closed!"); + break; + } + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + socket.close(); + } catch (IOException e) { + System.err.println("Socket isn`t closed!"); + } + } + } + + public static void main(String[] args) throws IOException { + readAphorismFile(); + try (ServerSocket serverSocket = new ServerSocket(3333)) { + while (true) { + System.out.println("The multithreaded server is started!"); + Socket socket = serverSocket.accept(); + try { + System.out.println("New connection is accepted from: " + socket.getRemoteSocketAddress()); + new AphorismsServer(socket); + } catch (IOException e) { + System.err.println(e); + socket.close(); + } + } + } + } + +} diff --git a/src/aphorisms/Controller.java b/src/aphorisms/Controller.java new file mode 100644 index 0000000..aa6baa2 --- /dev/null +++ b/src/aphorisms/Controller.java @@ -0,0 +1,47 @@ +package aphorisms; + +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.control.Button; +import javafx.scene.control.Label; +import javafx.scene.image.ImageView; + +import java.io.IOException; +import java.net.URL; +import java.util.ResourceBundle; + +; + + +public class Controller implements Initializable { + private AphorismClient aphorismClient = new AphorismClient(); + + @FXML + private Button show; + @FXML + private Button off; + @FXML + private Label display; + @FXML + private ImageView picture; + + @Override + public void initialize(URL location, ResourceBundle resources) { + System.out.println("Controllers is initialiaezed!"); + display.setWrapText(true); + } + + @FXML + private void clickShow () throws IOException { + aphorismClient.contactToServer(); + String toSet = aphorismClient.getAphorism(); + display.setText(toSet); + } + + @FXML + private void clickOff() throws IOException { + display.setText("I hope you like it! Bye!"); + aphorismClient.contactToServer(); + System.out.println("OFF"); + } +} diff --git a/src/aphorisms/V.jpg b/src/aphorisms/V.jpg new file mode 100644 index 0000000..f873376 Binary files /dev/null and b/src/aphorisms/V.jpg differ diff --git a/src/aphorisms/aphorisms.fxml b/src/aphorisms/aphorisms.fxml new file mode 100644 index 0000000..5c09f38 --- /dev/null +++ b/src/aphorisms/aphorisms.fxml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/electricClock/Balaton.jpg b/src/electricClock/Balaton.jpg new file mode 100644 index 0000000..d467c6e Binary files /dev/null and b/src/electricClock/Balaton.jpg differ diff --git a/src/electricClock/ClientElectricClock.java b/src/electricClock/ClientElectricClock.java new file mode 100644 index 0000000..111636f --- /dev/null +++ b/src/electricClock/ClientElectricClock.java @@ -0,0 +1,46 @@ +package electricClock; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.NoRouteToHostException; +import java.net.Socket; +import java.net.UnknownHostException; + +public class ClientElectricClock { + private Socket clientSocket; + private BufferedReader reader; + private BufferedReader incomingMessage; + private String actualTime; + + + public void contactToServer () throws IOException { + try { + System.out.println("The client is started!"); + clientSocket = new Socket("localhost", 1111); + reader = new BufferedReader(new InputStreamReader(System.in)); + incomingMessage = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + actualTime = incomingMessage.readLine(); + System.out.println("We received " + actualTime); + } catch (UnknownHostException e) { + System.out.println("The host isn`t found!"); + } catch (NoRouteToHostException e) { + System.out.println("The server isn`t available!"); + } catch (IOException e) { + System.out.println("The connection request is rejected!"); + } + reader.close(); + incomingMessage.close(); + clientSocket.close(); + System.out.println("The client is disconnected!"); + } + + public String getActualTime() { + return actualTime; + } + + public static void main(String[] args) throws IOException { + ClientElectricClock clientElectricClock = new ClientElectricClock(); + clientElectricClock.contactToServer(); + } +} diff --git a/src/electricClock/ServerElectricClock.java b/src/electricClock/ServerElectricClock.java new file mode 100644 index 0000000..53b8f0e --- /dev/null +++ b/src/electricClock/ServerElectricClock.java @@ -0,0 +1,43 @@ +package electricClock; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class ServerElectricClock { + private static Socket clientSocket; + private static ServerSocket serverSocket; + private static BufferedWriter outgoingMessage; + + public void receiveClient() throws IOException { + try { + serverSocket = new ServerSocket(1111); + System.out.println("The server is started!"); + while (true) { + clientSocket = serverSocket.accept(); + System.out.println("Connection is accepted from: " + clientSocket.getRemoteSocketAddress()); + try { + outgoingMessage = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yy HH:mm"); + Date actualDateAndTime = new Date(); + outgoingMessage.write(String.valueOf(dateFormat.format(actualDateAndTime))); + outgoingMessage.flush(); + } finally { + outgoingMessage.close(); + clientSocket.close(); + } + } + } catch (IOException e) { + System.err.println(e); + } + } + + public static void main(String[] args) throws IOException { + ServerElectricClock serverElectricClock = new ServerElectricClock(); + serverElectricClock.receiveClient(); + } +} diff --git a/src/messenger/Controller.java b/src/messenger/Controller.java new file mode 100644 index 0000000..93ea41f --- /dev/null +++ b/src/messenger/Controller.java @@ -0,0 +1,66 @@ +package messenger; + +import javafx.application.Platform; +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.control.Button; +import javafx.scene.control.Label; +import javafx.scene.control.TextField; +import javafx.scene.image.ImageView; + +import java.io.IOException; +import java.net.URL; +import java.util.ResourceBundle; + +public class Controller implements Initializable { + + @FXML + private Button show; + @FXML + private Button off; + @FXML + private Label display; + @FXML + private Label ID; + @FXML + private TextField id; + @FXML + private ImageView picture; + + MessengerClient messengerClient = new MessengerClient(111); + + @Override + public void initialize(URL location, ResourceBundle resources) { + System.out.println("Controllers is initialiaezed!"); + display.setWrapText(true); + id.setEditable(true); + + } + + @FXML + private void getMessage () throws IOException { + messengerClient.setId(Integer.parseInt(id.getText())); + id.setDisable(true); + Thread t1 = new Thread(new Runnable(){ + @Override + public void run() { + try { + messengerClient.contactToServer((String stringToSet) -> { + Platform.runLater(()-> display.setText(stringToSet)); + }); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + t1.start(); + } + + @FXML + private void clickOff() throws IOException { + display.setText("I hope you like it! Bye!"); + System.out.println("OFF"); + id.setDisable(false); + id.setEditable(true); + } +} diff --git a/src/messenger/Message.java b/src/messenger/Message.java new file mode 100644 index 0000000..f1f837b --- /dev/null +++ b/src/messenger/Message.java @@ -0,0 +1,40 @@ +package messenger; + +public class Message { + private String clientId; + private String msgText; + private String time; + private boolean last=false; + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getMsgText() { + return msgText; + } + + public void setMsgText(String msgText) { + this.msgText = msgText; + } + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public boolean isLast() { + return last; + } + + public void setLast(boolean last) { + this.last = last; + } +} diff --git a/src/messenger/MessengerClient.java b/src/messenger/MessengerClient.java new file mode 100644 index 0000000..1aba2b8 --- /dev/null +++ b/src/messenger/MessengerClient.java @@ -0,0 +1,71 @@ +package messenger; + +import java.io.*; +import java.net.NoRouteToHostException; +import java.net.Socket; +import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; +import java.util.function.Consumer; + +public class MessengerClient extends Thread { + private Socket clientSocket; + private BufferedReader incomingMessage; + private BufferedWriter outcomingMessage; + private int id; + private String newMessage; + + public MessengerClient (int id) { + this.id = id; + } + public void setId (int id){ + this.id = id; + } + + public void contactToServer () throws IOException { + contactToServer(null); + } + + public void contactToServer (Consumer callback) throws IOException { + try { + System.out.println("The client is started!"); + clientSocket = new Socket("localhost", 1003); + outcomingMessage = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); + String sendId = Integer.toString(id); + outcomingMessage.write(sendId); + outcomingMessage.write("\n"); + outcomingMessage.flush(); + System.out.println("The client " + id + " is connected!"); + incomingMessage = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8)); + while (true) { + newMessage = incomingMessage.readLine(); + if (newMessage != null){ + System.out.println("We received " + newMessage); + if (callback != null){ + callback.accept(newMessage); + } + } else { + break; + } + } + } catch (UnknownHostException e) { + System.out.println("The host isn`t found!"); + } catch (NoRouteToHostException e) { + System.out.println("The server isn`t available!"); + } catch (IOException e) { + System.out.println("The connection request is rejected!"); + } + if(incomingMessage != null){ + incomingMessage.close(); + } + if (clientSocket != null){ + clientSocket.close(); + } + System.out.println("The client is disconnected!"); + } + + public static void main(String[] args) throws IOException { + MessengerClient messengerClient = new MessengerClient(111); + messengerClient.contactToServer(); + } +} + diff --git a/src/messenger/MessengerServer.java b/src/messenger/MessengerServer.java new file mode 100644 index 0000000..687dd23 --- /dev/null +++ b/src/messenger/MessengerServer.java @@ -0,0 +1,169 @@ +package messenger; + +import org.apache.commons.io.FileUtils; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +public class MessengerServer extends Thread { + static volatile ConcurrentHashMap clientsMap = new ConcurrentHashMap(); + static private ArrayList clientMessages = new ArrayList<>(); + private Socket socket; + private PrintWriter outgoingMessage; + private BufferedReader incomingMessage; + private String clientId; + + public MessengerServer(Socket socket) throws IOException { + this.socket = socket; + incomingMessage = new BufferedReader(new InputStreamReader(socket.getInputStream())); + outgoingMessage = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); + start(); + } + + private static File resourcesToFile() { + try { + InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("Messeges.json"); + File temporaryFile = File.createTempFile("Temporary", ".tmp"); + temporaryFile.deleteOnExit(); + try (FileOutputStream outStream = new FileOutputStream(temporaryFile)) { + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outStream.write(buffer, 0, bytesRead); + } + } + return temporaryFile; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + static public void readMessages() { + String stringOfId; + JSONArray messages; + try { + File file = resourcesToFile(); + stringOfId = FileUtils.readFileToString(file, "utf-8"); + messages = new JSONArray(stringOfId); + } catch (IOException ex) { + System.out.println("Error during reading " + ex.getMessage()); + return; + } + for (int i = 0; i < messages.length(); i++) { + JSONObject mesJSON = (JSONObject) messages.get(i); + Message message = new Message(); + message.setClientId((String) mesJSON.get("id")); + message.setMsgText((String) mesJSON.get("mes")); + message.setTime((String) mesJSON.get("time")); + if(mesJSON.has("isLast") && (boolean) mesJSON.get("isLast")){ + message.setLast(true); + }else { + message.setLast(false); + } + clientMessages.add(message); + } + } + + public static void main(String[] args) throws IOException { + resourcesToFile(); + readMessages(); + Thread checkingMessage = new Thread (new Runnable() { + public void run() { + System.out.println("This is side thread!"); + while (true) { + SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); + String actualTime = dateFormat.format(new Date()); + System.out.println("Checking messages at " + actualTime); + for (Message msg : clientMessages) { + if (msg.getTime().equals(actualTime) && clientsMap.containsKey(msg.getClientId())) { + MessengerServer messengerServer = clientsMap.get(msg.getClientId()); + if (!Objects.isNull(messengerServer)){ + messengerServer.sendMessage(msg); + } + } + } + try { + Thread.sleep(60000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + }); + checkingMessage.start(); + + try (ServerSocket serverSocket = new ServerSocket(1003)) { + while (true) { + System.out.println("The multithread server is started!"); + Socket socket = serverSocket.accept(); + try { + System.out.println("New connection is accepted from: " + socket.getRemoteSocketAddress()); + new MessengerServer(socket); + } catch (IOException e) { + System.err.println(e); + socket.close(); + } + } + } + } + + public void run() { + try { + System.out.println("Waiting for incoming Message..."); + String id = incomingMessage.readLine(); + System.out.println("Client connected with ID: " + id); + if (id == null) { + System.out.println("Connection is closed!"); + } else { + clientId = id; + if (clientsMap.containsKey(id)){ + MessengerServer oldClient = clientsMap.get(id); + if(!Objects.isNull(oldClient)){ + oldClient.closeSocket(); + } + } + clientsMap.put(id, this); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void closeSocket(){ + try { + socket.close(); + outgoingMessage.close(); + incomingMessage.close(); + } catch (IOException e) { + System.err.println("Socket isn`t closed!"); + } + + } + + synchronized public void sendMessage(Message message) { + if (socket.isConnected()) { + System.out.println("Send message: " + message.getMsgText() + "to client id: " + clientId); + outgoingMessage.write(message.getMsgText()); + outgoingMessage.write("\n"); + outgoingMessage.flush(); + if(message.isLast()){ + closeSocket(); + if (clientsMap.containsKey(clientId)) + clientsMap.remove(clientId); + } + } else { + if (clientsMap.containsKey(clientId)) + clientsMap.remove(clientId); + } + } +} + diff --git a/src/messenger/Valencia.jpg b/src/messenger/Valencia.jpg new file mode 100644 index 0000000..f873376 Binary files /dev/null and b/src/messenger/Valencia.jpg differ diff --git a/src/messenger/messenger.fxml b/src/messenger/messenger.fxml new file mode 100644 index 0000000..da33173 --- /dev/null +++ b/src/messenger/messenger.fxml @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/messenger/messengerMain.java b/src/messenger/messengerMain.java new file mode 100644 index 0000000..bca57a0 --- /dev/null +++ b/src/messenger/messengerMain.java @@ -0,0 +1,25 @@ +package messenger; + +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Stage; + +import java.io.IOException; + +public class messengerMain extends Application { + + public static void main(String[] args) { + launch(args); + } + + @Override + public void start(Stage primaryStage) throws IOException { + Parent root = FXMLLoader.load(getClass().getResource("messenger.fxml")); + primaryStage.setTitle("Messenger"); + primaryStage.setScene(new Scene(root)); + primaryStage.setResizable(false); + primaryStage.show(); + } +}