From 1111e04db765a4cf38c54ffd4060760e161fb8ef Mon Sep 17 00:00:00 2001 From: maddojka Date: Sun, 14 Apr 2024 21:43:49 +0300 Subject: [PATCH 01/18] Server-client architecture - hometask --- client/src/com/soroko/client/ClientApp.java | 1 + 1 file changed, 1 insertion(+) diff --git a/client/src/com/soroko/client/ClientApp.java b/client/src/com/soroko/client/ClientApp.java index 2b63e55..41f9635 100644 --- a/client/src/com/soroko/client/ClientApp.java +++ b/client/src/com/soroko/client/ClientApp.java @@ -6,5 +6,6 @@ public class ClientApp { public static void main(String[] args) { new Client(new InetSocketAddress("127.0.0.1", 2222)) .startClient(); + System.out.println(); } } From b88da633495bbc0ef48213e4364270f0add73d95 Mon Sep 17 00:00:00 2001 From: maddojka Date: Thu, 2 May 2024 21:42:30 +0300 Subject: [PATCH 02/18] Server-client course work --- client/src/com/soroko/client/Client.java | 95 +++++-- client/src/com/soroko/client/ClientApp.java | 1 - common/src/com/soroko/common/FileHandler.java | 14 + common/src/com/soroko/common/FileMessage.java | 11 + .../soroko/common/{common => }/Message.java | 14 +- common/src/com/soroko/common/SendReceive.java | 62 +++++ .../src/com/soroko/common/WriteMessage.java | 41 +++ .../com/soroko/common/common/SendReceive.java | 40 --- common/src/module-info.java | 2 +- server/src/com/soroko/server/Server.java | 250 ++++++++++++++---- 10 files changed, 413 insertions(+), 117 deletions(-) create mode 100644 common/src/com/soroko/common/FileHandler.java create mode 100644 common/src/com/soroko/common/FileMessage.java rename common/src/com/soroko/common/{common => }/Message.java (68%) create mode 100644 common/src/com/soroko/common/SendReceive.java create mode 100644 common/src/com/soroko/common/WriteMessage.java delete mode 100644 common/src/com/soroko/common/common/SendReceive.java diff --git a/client/src/com/soroko/client/Client.java b/client/src/com/soroko/client/Client.java index 8dd8583..3c5e493 100644 --- a/client/src/com/soroko/client/Client.java +++ b/client/src/com/soroko/client/Client.java @@ -1,7 +1,8 @@ package com.soroko.client; -import com.soroko.common.common.SendReceive; -import com.soroko.common.common.Message; +import com.soroko.common.FileMessage; +import com.soroko.common.SendReceive; +import com.soroko.common.Message; import java.io.IOException; import java.net.InetSocketAddress; @@ -12,40 +13,94 @@ public class Client { private InetSocketAddress address; private String username; private Scanner scanner; + private SendReceive connectionHandler; public Client(InetSocketAddress address) { this.address = address; scanner = new Scanner(System.in); } - - - public void startClient() { - System.out.println("Введите имя"); - username = scanner.nextLine(); - while (true) { - System.out.println("Введите текст сообщения"); - String text = scanner.nextLine(); - if (text.equals("/exit")) break; - try (SendReceive connectionHandler - = new SendReceive(new Socket( - address.getHostName(), - address.getPort() - ))) { + private class Writer extends Thread { + public void run() { + boolean isLoadCommand = false; + while (true) { + if (!isLoadCommand) System.out.println("Введите текст сообщения"); + else { + System.out.println("Введите путь, по которому необходимо загрузить файл на сервер"); + // isLoadCommand = false; + } + String text = scanner.nextLine(); + if (isLoadCommand) { + System.out.println("Введите описание файла:"); + String description = scanner.nextLine(); + System.out.println("Введите размер файла:"); + int size = scanner.nextInt(); + // FileMessage fileMessage = new FileMessage(description, size); + // try { + // connectionHandler.sendFileDescription(fileMessage); + // } catch (IOException e) { + // connectionHandler.close(); + // System.out.println("filedescription"); + // } + isLoadCommand = false; + } + if (text.equalsIgnoreCase("/loadfile")) isLoadCommand = true; + if (text.equalsIgnoreCase("/exit")) { + System.out.println("Соединение прекращено"); + connectionHandler.close(); + break; + } Message message = new Message(username); message.setText(text); try { connectionHandler.send(message); - Message fromServer = connectionHandler.receive(); - System.out.println(fromServer.getText()); - } catch (IOException e) { + } catch (IOException ignored) { + connectionHandler.close(); } + } + } + } - } catch (Exception e) { + private class Reader extends Thread { + public void run() { + while (true) { + Message message; + try { + message = connectionHandler.receive(); + if (message.getText().equalsIgnoreCase("/exit")) { + connectionHandler.close(); + break; + } + } catch (IOException ignored) { + connectionHandler.close(); + break; + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + System.out.println(message.getText()); } } } + + public void createConnection() throws IOException { + connectionHandler = new SendReceive( + new Socket(address.getHostName(), address.getPort())); + } + + public void startClient() { + System.out.println("Введите имя"); + username = scanner.nextLine(); + try { + createConnection(); + } catch (IOException e) { + throw new RuntimeException(e); + } + new Writer().start(); + new Reader().start(); + } } + + diff --git a/client/src/com/soroko/client/ClientApp.java b/client/src/com/soroko/client/ClientApp.java index 41f9635..2b63e55 100644 --- a/client/src/com/soroko/client/ClientApp.java +++ b/client/src/com/soroko/client/ClientApp.java @@ -6,6 +6,5 @@ public class ClientApp { public static void main(String[] args) { new Client(new InetSocketAddress("127.0.0.1", 2222)) .startClient(); - System.out.println(); } } diff --git a/common/src/com/soroko/common/FileHandler.java b/common/src/com/soroko/common/FileHandler.java new file mode 100644 index 0000000..072464f --- /dev/null +++ b/common/src/com/soroko/common/FileHandler.java @@ -0,0 +1,14 @@ +package com.soroko.common; + +import java.io.File; + +public class FileHandler { + private File file; + private String filename; + + public FileHandler(File file, String filename) { + this.filename = filename; + this.file = file; + } + +} diff --git a/common/src/com/soroko/common/FileMessage.java b/common/src/com/soroko/common/FileMessage.java new file mode 100644 index 0000000..fe1928d --- /dev/null +++ b/common/src/com/soroko/common/FileMessage.java @@ -0,0 +1,11 @@ +package com.soroko.common; + +public class FileMessage { + private String description; + private int size; + + public FileMessage(String description, int size) { + this.description = description; + this.size = size; + } +} diff --git a/common/src/com/soroko/common/common/Message.java b/common/src/com/soroko/common/Message.java similarity index 68% rename from common/src/com/soroko/common/common/Message.java rename to common/src/com/soroko/common/Message.java index 7dde2df..6bbc49a 100644 --- a/common/src/com/soroko/common/common/Message.java +++ b/common/src/com/soroko/common/Message.java @@ -1,12 +1,14 @@ -package com.soroko.common.common; +package com.soroko.common; import java.io.Serializable; +import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; public class Message implements Serializable { - String sender; - String text; - LocalDateTime sentAt; + private String sender; + private String text; + private String sentAt; public Message(String sender) { this.sender = sender; @@ -28,11 +30,11 @@ public void setText(String text) { this.text = text; } - public LocalDateTime getSentAt() { + public String getSentAt() { return sentAt; } - public void setSentAt(LocalDateTime sentAt) { + public void setSentAt(String sentAt) { this.sentAt = sentAt; } } diff --git a/common/src/com/soroko/common/SendReceive.java b/common/src/com/soroko/common/SendReceive.java new file mode 100644 index 0000000..a71ac47 --- /dev/null +++ b/common/src/com/soroko/common/SendReceive.java @@ -0,0 +1,62 @@ +package com.soroko.common; + +import java.io.*; +import java.net.Socket; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.Objects; + +public class SendReceive implements AutoCloseable { + private ObjectOutputStream outputStream; + private ObjectInputStream inputStream; + private Socket socket; + + + + public SendReceive(Socket socket) throws IOException { + this.socket = Objects.requireNonNull(socket); + outputStream = new ObjectOutputStream(socket.getOutputStream()); + inputStream = new ObjectInputStream(socket.getInputStream()); + } + + + public void send(Message message) throws IOException { + DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("HH:mm:ss"); + LocalTime localTime = LocalTime.now(); + message.setSentAt(localTime.format(formatTime)); + outputStream.writeObject(message); + outputStream.flush(); + } + + public void sendFileDescription(FileMessage fileMessage) throws IOException { + outputStream.writeObject(fileMessage); + outputStream.flush(); + } + + public Message receive() throws IOException, ClassNotFoundException { + try { + return (Message) inputStream.readObject(); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + + public FileMessage receiveFileDescription() throws IOException, ClassNotFoundException { + return (FileMessage) inputStream.readObject(); + } + + @Override + public void close() { + try { + if (!socket.isClosed()) { + inputStream.close(); + outputStream.close(); + socket.close(); + } + } catch (IOException ignored) { + System.out.println("Проблема при закрытии потоков"); + } + + } +} diff --git a/common/src/com/soroko/common/WriteMessage.java b/common/src/com/soroko/common/WriteMessage.java new file mode 100644 index 0000000..e1d28f0 --- /dev/null +++ b/common/src/com/soroko/common/WriteMessage.java @@ -0,0 +1,41 @@ +package com.soroko.common; + +import java.io.IOException; +import java.util.Scanner; + +public class WriteMessage extends Thread { + SendReceive connectionHandler; + private String username; + private Scanner scanner; + private int counter; + + public WriteMessage(SendReceive sendReceive, String username, Scanner scanner) { + this.connectionHandler = sendReceive; + this.username = username; + this.scanner = scanner; + } + + @Override + public void run() { + System.out.println("Введите имя"); + username = scanner.nextLine(); + + while(true) { + System.out.println("Введите текст сообщения"); + String text = scanner.nextLine(); + if (text.equals("/exit")) break; + Message message = new Message(username); + message.setText(text); + try { + Message fromServer = null; + try { + fromServer = connectionHandler.receive(); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + System.out.println(fromServer.getText()); + } catch (IOException e) { + } + } + } +} diff --git a/common/src/com/soroko/common/common/SendReceive.java b/common/src/com/soroko/common/common/SendReceive.java deleted file mode 100644 index 9de2152..0000000 --- a/common/src/com/soroko/common/common/SendReceive.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.soroko.common.common; - -import java.io.*; -import java.net.Socket; -import java.time.Instant; -import java.time.LocalDateTime; - -public class SendReceive implements AutoCloseable { - private ObjectOutputStream outputStream; - private ObjectInputStream inputStream; - private Socket socket; - - - - public SendReceive(Socket socket) throws IOException { - outputStream = new ObjectOutputStream(socket.getOutputStream()); - inputStream = new ObjectInputStream(socket.getInputStream()); - } - - public void send(Message message) throws IOException { - message.setSentAt(LocalDateTime.now()); - outputStream.writeObject(message); - outputStream.flush(); - } - - public Message receive() throws IOException, ClassNotFoundException { - try { - return (Message) inputStream.readObject(); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - - @Override - public void close() throws Exception { - inputStream.close(); - outputStream.close(); - socket.close(); - } -} diff --git a/common/src/module-info.java b/common/src/module-info.java index bb555eb..7483ae2 100644 --- a/common/src/module-info.java +++ b/common/src/module-info.java @@ -1,3 +1,3 @@ module common { - exports com.soroko.common.common; + exports com.soroko.common; } \ No newline at end of file diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index dbc1fe5..48c6117 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -1,78 +1,230 @@ package com.soroko.server; +import com.soroko.common.*; -import com.soroko.common.common.Message; -import com.soroko.common.common.SendReceive; - -import java.io.IOException; +import java.io.*; import java.net.ServerSocket; import java.net.Socket; -import java.util.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.stream.Collectors; public class Server { - private int port; - private int reqCounter = 0; - private long elapsedTime; - private int helpCounter = 0; - private int pingCounter = 0; - private int requestsCounter = 0; - private int popularCounter = 0; - - private Map requests = new HashMap<>(); + public static final String SERVER_STORAGE_LOCATION = + "C:\\Users\\yuriy\\IdeaProjects\\socketLesson\\server\\src\\com\\soroko\\server\\"; + private final int port; + private final ArrayBlockingQueue messages = + new ArrayBlockingQueue<>(1000, true); + private final List connectionHandlers = new CopyOnWriteArrayList<>(); + Sender sender; + ThreadForClient threadForClient; + SendReceive connectionHandler; + private long fileSize; + private int amountOfSymbols; + private int randomName; + ArrayList files = new ArrayList<>(); public Server(int port) { this.port = port; + fileSize = 10_000_000_000L; + amountOfSymbols = 200; + } + + public int countSymbol(File file) { + BufferedReader reader; + int count = 0; + try { + reader = new BufferedReader(new FileReader(file)); + while (reader.ready()) { + for (char symbol : reader.readLine().toCharArray()) { + count++; + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + return count; + } + + public synchronized void showFiles() { + Message message = new Message("server"); + String intro = "Список доступных файлов:" + "\n"; + String fileNames = files.stream().map(File::getName).collect(Collectors.joining(", ")); + if (files.isEmpty()) message.setText("Доступных файлов не обнаружено"); + else message.setText(intro + fileNames); + try { + connectionHandler.send(message); + } catch (IOException e) { + connectionHandler.close(); + } } - public String makeRequest(String text) { - if (text.equals("/help")) { - reqCounter++; - requests.put("/help", ++helpCounter); - return "/help - список доступных запросов и их описание\n" + - "/ping - время ответа сервера\n" + - "/requests - количество успешно обработанных запросов\n" + - "/popular - название самого популярного запроса\n" + - "/exit - завершить соединение с сервером"; - } else if (text.equals("/ping")) { - reqCounter++; - requests.put("ping", ++pingCounter); - return elapsedTime + " ms"; - } else if (text.equals("/requests")) { - reqCounter++; - requests.put("requests", ++requestsCounter); - return String.valueOf(reqCounter); - } else if (text.equals("/popular")) { - reqCounter++; - requests.put("popular", ++popularCounter); - return requests.entrySet().stream() - .max(Comparator.comparingInt(Map.Entry::getValue)) - .orElseGet(null) - .toString(); + public synchronized void loadFile(String pathname) { + randomName = (int) (Math.random() * 1000); + File fileSource = new File(pathname); + String fileName = SERVER_STORAGE_LOCATION + fileSource.getName(); + String fileWasCreated; + File fileDestination; + Path path = Paths.get(fileName); + if (Files.exists(path)) { + fileDestination = + new File((SERVER_STORAGE_LOCATION + randomName + fileSource.getName())); } else { - return "Невозможно обработать запрос"; + fileDestination = new File(fileName); + } + if (!fileSource.isDirectory() && fileSource.exists()) { + long bytes = fileSource.length(); + int symbols = countSymbol(fileSource); + + if (bytes <= fileSize && symbols <= amountOfSymbols) { + try { + copy(fileSource, fileDestination); + if (fileDestination.isFile()) + files.add(fileDestination); + fileWasCreated = "Файл " + fileDestination.getName() + " был успешно загружен"; + Message fileWasCreatedMessage = new Message("server"); + fileWasCreatedMessage.setText(fileWasCreated); + try { + messages.put(fileWasCreatedMessage); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } else { + String fileDoesNotExist = "Файл по указанному пути не найден" + + " или содержит слишком большой объем информации"; + Message fileDoesNotExistMsg = new Message("server"); + fileDoesNotExistMsg.setText(fileDoesNotExist); + try { + connectionHandler.send(fileDoesNotExistMsg); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + } + + synchronized void saveFile(String fileName) { + for (File file : files) { + if (fileName.equals(file.getName())) { + } } } public void startServer() { try (ServerSocket serverSocket = new ServerSocket(port)) { + sender = new Sender(); + sender.start(); while (true) { try { Socket socket = serverSocket.accept(); - long startTime = System.nanoTime(); - SendReceive connetionHandler = new SendReceive(socket); - Message fromClient = connetionHandler.receive(); - String fromServer = makeRequest(fromClient.getText()); - Message message = new Message("server"); - message.setText(fromServer); - connetionHandler.send(message); - elapsedTime = (System.nanoTime() - startTime) / 1_000_000L; + // SendReceive connectionHandler = new SendReceive(socket); + connectionHandler = new SendReceive(socket); + connectionHandlers.add(connectionHandler); + threadForClient = new ThreadForClient(connectionHandler); + threadForClient.start(); } catch (Exception e) { - System.out.println("Проблема с соединением"); + System.out.println("Проблема с установкой нового соединения"); } } } catch (IOException e) { System.out.println("Ошибка запуска сервера"); + throw new RuntimeException(e); + } + } + + public static void copy(File source, File dest) throws IOException { + Files.copy(source.toPath(), dest.toPath()); + } + + private class ThreadForClient extends Thread { + private final SendReceive connectionHandler; + Message fromClient; + + public ThreadForClient(SendReceive connectionHandler) { + this.connectionHandler = connectionHandler; + } + + public SendReceive getConnectionHandler() { + return connectionHandler; + } + + public Message getFromClient() { + return fromClient; + } + + @Override + public void run() { + while (true) { + fromClient = null; + try { + fromClient = connectionHandler.receive(); + } catch (IOException e) { + connectionHandlers.remove(connectionHandler); + return; + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + if (!fromClient.getText().equals("/files") && !fromClient.getText().equals("/loadfile") + && !fromClient.getText().equals("/savefile")) { + Message message = new Message("server: " + fromClient.getSender()); + message.setText(fromClient.getSentAt() + " " + + fromClient.getSender() + ": " + fromClient.getText()); + try { + messages.put(message); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + } + } else if (fromClient.getText().equals("/files")) { + showFiles(); + } else if (fromClient.getText().equals("/loadfile")) { + Message pathMessage; + // FileMessage fileMessage; + try { + pathMessage = connectionHandler.receive(); + // fileMessage = connectionHandler.receiveFileDescription(); + } catch (IOException e) { + connectionHandlers.remove(connectionHandler); + return; + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + loadFile(pathMessage.getText()); + } else if (fromClient.getText().equals("/savefile")) { + saveFile("fileName"); + } + } + } + } + + private class Sender extends Thread { + @Override + public void run() { + while (!Thread.currentThread().isInterrupted()) { // true + try { + Message message = messages.take(); + for (SendReceive handler : connectionHandlers) { + try { + handler.send(message); + } catch (IOException e) { + connectionHandlers.remove(handler); + } + } + + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + Thread.currentThread().interrupt(); + } + } } } -} +} \ No newline at end of file From 1b013d5ee047939a9e900113880e539a578f2004 Mon Sep 17 00:00:00 2001 From: maddojka Date: Thu, 2 May 2024 23:10:14 +0300 Subject: [PATCH 03/18] Server-client course work --- client/src/com/soroko/client/Client.java | 27 +++++----- common/src/com/soroko/common/FileHandler.java | 14 ----- common/src/com/soroko/common/FileMessage.java | 21 +++++++- common/src/com/soroko/common/SendReceive.java | 6 ++- server/src/com/soroko/server/Server.java | 51 +++++++------------ 5 files changed, 57 insertions(+), 62 deletions(-) delete mode 100644 common/src/com/soroko/common/FileHandler.java diff --git a/client/src/com/soroko/client/Client.java b/client/src/com/soroko/client/Client.java index 3c5e493..2ed5438 100644 --- a/client/src/com/soroko/client/Client.java +++ b/client/src/com/soroko/client/Client.java @@ -27,23 +27,26 @@ public void run() { if (!isLoadCommand) System.out.println("Введите текст сообщения"); else { System.out.println("Введите путь, по которому необходимо загрузить файл на сервер"); - // isLoadCommand = false; - } - String text = scanner.nextLine(); - if (isLoadCommand) { + // isLoadCommand = false; + String filepath = scanner.nextLine(); System.out.println("Введите описание файла:"); String description = scanner.nextLine(); - System.out.println("Введите размер файла:"); + System.out.println("Введите размер файла в мегабайтах:"); int size = scanner.nextInt(); - // FileMessage fileMessage = new FileMessage(description, size); - // try { - // connectionHandler.sendFileDescription(fileMessage); - // } catch (IOException e) { - // connectionHandler.close(); - // System.out.println("filedescription"); - // } + FileMessage fileMessage = new FileMessage(description, size); + fileMessage.setFilepath(filepath); + try { + connectionHandler.sendFileDescription(fileMessage); + } catch (IOException e) { + connectionHandler.close(); + System.out.println("filedescription"); + } isLoadCommand = false; } + String text = scanner.nextLine(); + // if (isLoadCommand) { + + // } if (text.equalsIgnoreCase("/loadfile")) isLoadCommand = true; if (text.equalsIgnoreCase("/exit")) { System.out.println("Соединение прекращено"); diff --git a/common/src/com/soroko/common/FileHandler.java b/common/src/com/soroko/common/FileHandler.java deleted file mode 100644 index 072464f..0000000 --- a/common/src/com/soroko/common/FileHandler.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.soroko.common; - -import java.io.File; - -public class FileHandler { - private File file; - private String filename; - - public FileHandler(File file, String filename) { - this.filename = filename; - this.file = file; - } - -} diff --git a/common/src/com/soroko/common/FileMessage.java b/common/src/com/soroko/common/FileMessage.java index fe1928d..032679a 100644 --- a/common/src/com/soroko/common/FileMessage.java +++ b/common/src/com/soroko/common/FileMessage.java @@ -1,11 +1,30 @@ package com.soroko.common; -public class FileMessage { +import java.io.Serializable; + +public class FileMessage implements Serializable { private String description; private int size; + private String filepath; public FileMessage(String description, int size) { this.description = description; this.size = size; } + + public String getFilepath() { + return filepath; + } + + public void setFilepath(String filepath) { + this.filepath = filepath; + } + + public String getDescription() { + return description; + } + + public int getSize() { + return size; + } } diff --git a/common/src/com/soroko/common/SendReceive.java b/common/src/com/soroko/common/SendReceive.java index a71ac47..a69969c 100644 --- a/common/src/com/soroko/common/SendReceive.java +++ b/common/src/com/soroko/common/SendReceive.java @@ -43,7 +43,11 @@ public Message receive() throws IOException, ClassNotFoundException { } public FileMessage receiveFileDescription() throws IOException, ClassNotFoundException { - return (FileMessage) inputStream.readObject(); + try { + return (FileMessage) inputStream.readObject(); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } } @Override diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 48c6117..35f6d4b 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -25,33 +25,17 @@ public class Server { Sender sender; ThreadForClient threadForClient; SendReceive connectionHandler; - private long fileSize; + private int fileSize; private int amountOfSymbols; private int randomName; ArrayList files = new ArrayList<>(); public Server(int port) { this.port = port; - fileSize = 10_000_000_000L; + fileSize = 10; amountOfSymbols = 200; } - public int countSymbol(File file) { - BufferedReader reader; - int count = 0; - try { - reader = new BufferedReader(new FileReader(file)); - while (reader.ready()) { - for (char symbol : reader.readLine().toCharArray()) { - count++; - } - } - } catch (IOException e) { - throw new RuntimeException(e); - } - return count; - } - public synchronized void showFiles() { Message message = new Message("server"); String intro = "Список доступных файлов:" + "\n"; @@ -65,9 +49,10 @@ public synchronized void showFiles() { } } - public synchronized void loadFile(String pathname) { + public synchronized void loadFile(/*String pathname*/ FileMessage fileMessage) { randomName = (int) (Math.random() * 1000); - File fileSource = new File(pathname); + char[] descriptionChars = fileMessage.getDescription().toCharArray(); + File fileSource = new File(fileMessage.getFilepath()); String fileName = SERVER_STORAGE_LOCATION + fileSource.getName(); String fileWasCreated; File fileDestination; @@ -79,15 +64,12 @@ public synchronized void loadFile(String pathname) { fileDestination = new File(fileName); } if (!fileSource.isDirectory() && fileSource.exists()) { - long bytes = fileSource.length(); - int symbols = countSymbol(fileSource); - - if (bytes <= fileSize && symbols <= amountOfSymbols) { + if (fileMessage.getSize() <= fileSize && descriptionChars.length <= amountOfSymbols) { try { copy(fileSource, fileDestination); if (fileDestination.isFile()) files.add(fileDestination); - fileWasCreated = "Файл " + fileDestination.getName() + " был успешно загружен"; + fileWasCreated = "Файл " + fileDestination.getName() + " был успешно загружен"; Message fileWasCreatedMessage = new Message("server"); fileWasCreatedMessage.setText(fileWasCreated); try { @@ -110,10 +92,9 @@ public synchronized void loadFile(String pathname) { System.out.println(e.getMessage()); } } - } - synchronized void saveFile(String fileName) { + synchronized void saveFile(String fileName) { for (File file : files) { if (fileName.equals(file.getName())) { } @@ -174,7 +155,8 @@ public void run() { } catch (ClassNotFoundException e) { throw new RuntimeException(e); } - if (!fromClient.getText().equals("/files") && !fromClient.getText().equals("/loadfile") + if (fromClient != null && !fromClient.getText().equals("/files") + && !fromClient.getText().equals("/loadfile") && !fromClient.getText().equals("/savefile")) { Message message = new Message("server: " + fromClient.getSender()); message.setText(fromClient.getSentAt() + " " @@ -187,18 +169,18 @@ public void run() { } else if (fromClient.getText().equals("/files")) { showFiles(); } else if (fromClient.getText().equals("/loadfile")) { - Message pathMessage; - // FileMessage fileMessage; + // Message pathMessage; + FileMessage fileMessage; try { - pathMessage = connectionHandler.receive(); - // fileMessage = connectionHandler.receiveFileDescription(); + // pathMessage = connectionHandler.receive(); + fileMessage = connectionHandler.receiveFileDescription(); } catch (IOException e) { connectionHandlers.remove(connectionHandler); return; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } - loadFile(pathMessage.getText()); + loadFile(fileMessage); } else if (fromClient.getText().equals("/savefile")) { saveFile("fileName"); } @@ -214,7 +196,8 @@ public void run() { Message message = messages.take(); for (SendReceive handler : connectionHandlers) { try { - handler.send(message); + if (handler != null) + handler.send(message); } catch (IOException e) { connectionHandlers.remove(handler); } From 99ee40b8b0465cc2649fe9d17bca9ed260417b3b Mon Sep 17 00:00:00 2001 From: maddojka Date: Sat, 4 May 2024 23:09:50 +0300 Subject: [PATCH 04/18] Server-client course work --- client/src/com/soroko/client/Client.java | 24 +++++++---- common/src/com/soroko/common/FileMessage.java | 14 +++++++ .../src/com/soroko/common/WriteMessage.java | 2 +- server/src/com/soroko/server/Server.java | 40 +++++++++++++++---- 4 files changed, 64 insertions(+), 16 deletions(-) diff --git a/client/src/com/soroko/client/Client.java b/client/src/com/soroko/client/Client.java index 2ed5438..16e3c90 100644 --- a/client/src/com/soroko/client/Client.java +++ b/client/src/com/soroko/client/Client.java @@ -23,11 +23,11 @@ public Client(InetSocketAddress address) { private class Writer extends Thread { public void run() { boolean isLoadCommand = false; + boolean isSaveCommand = false; while (true) { - if (!isLoadCommand) System.out.println("Введите текст сообщения"); - else { + if (!isLoadCommand && !isSaveCommand) System.out.println("Введите текст сообщения"); + else if (isLoadCommand) { System.out.println("Введите путь, по которому необходимо загрузить файл на сервер"); - // isLoadCommand = false; String filepath = scanner.nextLine(); System.out.println("Введите описание файла:"); String description = scanner.nextLine(); @@ -39,15 +39,25 @@ public void run() { connectionHandler.sendFileDescription(fileMessage); } catch (IOException e) { connectionHandler.close(); - System.out.println("filedescription"); } isLoadCommand = false; + } else if (isSaveCommand) { + System.out.println("Укажите папку, в которую необходимо загрузить файл из сервера"); + String filepath = scanner.nextLine(); + System.out.println("Введите название файла из списка доступных файлов:"); + String description = scanner.nextLine(); + FileMessage fileMessage = new FileMessage(description, filepath); + fileMessage.setFilepath(filepath); + try { + connectionHandler.sendFileDescription(fileMessage); + } catch (IOException e) { + connectionHandler.close(); + } + isSaveCommand = false; } String text = scanner.nextLine(); - // if (isLoadCommand) { - - // } if (text.equalsIgnoreCase("/loadfile")) isLoadCommand = true; + if (text.equalsIgnoreCase("/savefile")) isSaveCommand = true; if (text.equalsIgnoreCase("/exit")) { System.out.println("Соединение прекращено"); connectionHandler.close(); diff --git a/common/src/com/soroko/common/FileMessage.java b/common/src/com/soroko/common/FileMessage.java index 032679a..ed83e7c 100644 --- a/common/src/com/soroko/common/FileMessage.java +++ b/common/src/com/soroko/common/FileMessage.java @@ -6,6 +6,12 @@ public class FileMessage implements Serializable { private String description; private int size; private String filepath; + private boolean isEmpty; + + public FileMessage(String description, String filepath) { + this.description = description; + this.filepath = filepath; + } public FileMessage(String description, int size) { this.description = description; @@ -27,4 +33,12 @@ public String getDescription() { public int getSize() { return size; } + + public void setEmpty(boolean empty) { + isEmpty = empty; + } + + public boolean isEmpty() { + return isEmpty; + } } diff --git a/common/src/com/soroko/common/WriteMessage.java b/common/src/com/soroko/common/WriteMessage.java index e1d28f0..3b47349 100644 --- a/common/src/com/soroko/common/WriteMessage.java +++ b/common/src/com/soroko/common/WriteMessage.java @@ -27,7 +27,7 @@ public void run() { Message message = new Message(username); message.setText(text); try { - Message fromServer = null; + Message fromServer; try { fromServer = connectionHandler.receive(); } catch (ClassNotFoundException e) { diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 35f6d4b..9bbee19 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -10,6 +10,7 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; @@ -49,7 +50,7 @@ public synchronized void showFiles() { } } - public synchronized void loadFile(/*String pathname*/ FileMessage fileMessage) { + public synchronized void loadFile(FileMessage fileMessage) { randomName = (int) (Math.random() * 1000); char[] descriptionChars = fileMessage.getDescription().toCharArray(); File fileSource = new File(fileMessage.getFilepath()); @@ -94,10 +95,25 @@ public synchronized void loadFile(/*String pathname*/ FileMessage fileMessage) { } } - synchronized void saveFile(String fileName) { - for (File file : files) { - if (fileName.equals(file.getName())) { + synchronized void saveFile(FileMessage fileMessage) { + File fileSource = + new File((SERVER_STORAGE_LOCATION + fileMessage.getDescription())); + File fileDestination = new File(fileMessage.getFilepath() + fileMessage.getDescription()); + String fileWasCreated; + try { + copy(fileSource, fileDestination); + if (fileDestination.isFile()) { + fileWasCreated = "Файл " + fileDestination.getName() + " был успешно сохранен с сервера"; + Message fileWasCreatedMessage = new Message("server"); + fileWasCreatedMessage.setText(fileWasCreated); + try { + messages.put(fileWasCreatedMessage); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + } } + } catch (IOException e) { + throw new RuntimeException(e); } } @@ -166,13 +182,11 @@ public void run() { } catch (InterruptedException e) { System.out.println(e.getMessage()); } - } else if (fromClient.getText().equals("/files")) { + } else if (Objects.requireNonNull(fromClient).getText().equals("/files")) { showFiles(); } else if (fromClient.getText().equals("/loadfile")) { - // Message pathMessage; FileMessage fileMessage; try { - // pathMessage = connectionHandler.receive(); fileMessage = connectionHandler.receiveFileDescription(); } catch (IOException e) { connectionHandlers.remove(connectionHandler); @@ -182,7 +196,17 @@ public void run() { } loadFile(fileMessage); } else if (fromClient.getText().equals("/savefile")) { - saveFile("fileName"); + showFiles(); + FileMessage fileMessage; + try { + fileMessage = connectionHandler.receiveFileDescription(); + } catch (IOException e) { + connectionHandlers.remove(connectionHandler); + return; + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + saveFile(fileMessage); } } } From f085ada8989a1b2e8b203b220bbe0633115bd52f Mon Sep 17 00:00:00 2001 From: maddojka Date: Sun, 5 May 2024 11:32:53 +0300 Subject: [PATCH 05/18] Server-client course work - minor changes --- client/src/com/soroko/client/Client.java | 63 +++++++++++-------- common/src/com/soroko/common/FileMessage.java | 27 ++++---- common/src/com/soroko/common/Message.java | 9 +++ server/src/com/soroko/server/Server.java | 36 +++++++---- 4 files changed, 84 insertions(+), 51 deletions(-) diff --git a/client/src/com/soroko/client/Client.java b/client/src/com/soroko/client/Client.java index 16e3c90..6af10e8 100644 --- a/client/src/com/soroko/client/Client.java +++ b/client/src/com/soroko/client/Client.java @@ -14,47 +14,55 @@ public class Client { private String username; private Scanner scanner; private SendReceive connectionHandler; + private boolean isEmpty; public Client(InetSocketAddress address) { this.address = address; scanner = new Scanner(System.in); } + public void saveCommand() { + System.out.println("Укажите папку, в которую необходимо загрузить файл из сервера"); + String filepath = scanner.nextLine(); + System.out.println("Введите название файла из списка доступных файлов:"); + String description = scanner.nextLine(); + FileMessage fileMessage = new FileMessage(description, filepath); + fileMessage.setFilePath(filepath); + try { + connectionHandler.sendFileDescription(fileMessage); + } catch (IOException e) { + connectionHandler.close(); + } + } + + public void loadCommand() { + System.out.println("Введите путь, по которому необходимо загрузить файл на сервер"); + String filepath = scanner.nextLine(); + System.out.println("Введите описание файла:"); + String description = scanner.nextLine(); + System.out.println("Введите размер файла в мегабайтах:"); + int size = scanner.nextInt(); + FileMessage fileMessage = new FileMessage(description, size); + fileMessage.setFilePath(filepath); + try { + connectionHandler.sendFileDescription(fileMessage); + } catch (IOException e) { + connectionHandler.close(); + } + } + private class Writer extends Thread { public void run() { boolean isLoadCommand = false; boolean isSaveCommand = false; while (true) { - if (!isLoadCommand && !isSaveCommand) System.out.println("Введите текст сообщения"); - else if (isLoadCommand) { - System.out.println("Введите путь, по которому необходимо загрузить файл на сервер"); - String filepath = scanner.nextLine(); - System.out.println("Введите описание файла:"); - String description = scanner.nextLine(); - System.out.println("Введите размер файла в мегабайтах:"); - int size = scanner.nextInt(); - FileMessage fileMessage = new FileMessage(description, size); - fileMessage.setFilepath(filepath); - try { - connectionHandler.sendFileDescription(fileMessage); - } catch (IOException e) { - connectionHandler.close(); - } + if (isLoadCommand) { + loadCommand(); isLoadCommand = false; } else if (isSaveCommand) { - System.out.println("Укажите папку, в которую необходимо загрузить файл из сервера"); - String filepath = scanner.nextLine(); - System.out.println("Введите название файла из списка доступных файлов:"); - String description = scanner.nextLine(); - FileMessage fileMessage = new FileMessage(description, filepath); - fileMessage.setFilepath(filepath); - try { - connectionHandler.sendFileDescription(fileMessage); - } catch (IOException e) { - connectionHandler.close(); - } + saveCommand(); isSaveCommand = false; - } + } else System.out.println("Введите текст сообщения"); String text = scanner.nextLine(); if (text.equalsIgnoreCase("/loadfile")) isLoadCommand = true; if (text.equalsIgnoreCase("/savefile")) isSaveCommand = true; @@ -91,6 +99,7 @@ public void run() { throw new RuntimeException(e); } System.out.println(message.getText()); + if (message.isEmpty()) isEmpty = true; } } } diff --git a/common/src/com/soroko/common/FileMessage.java b/common/src/com/soroko/common/FileMessage.java index ed83e7c..f4f84e1 100644 --- a/common/src/com/soroko/common/FileMessage.java +++ b/common/src/com/soroko/common/FileMessage.java @@ -1,16 +1,17 @@ package com.soroko.common; import java.io.Serializable; +import java.nio.file.Paths; public class FileMessage implements Serializable { private String description; private int size; - private String filepath; - private boolean isEmpty; + private String filePath; + public FileMessage(String description, String filepath) { this.description = description; - this.filepath = filepath; + this.filePath = filepath; } public FileMessage(String description, int size) { @@ -18,12 +19,12 @@ public FileMessage(String description, int size) { this.size = size; } - public String getFilepath() { - return filepath; + public String getFilePath() { + return filePath; } - public void setFilepath(String filepath) { - this.filepath = filepath; + public void setFilePath(String filePath) { + this.filePath = filePath; } public String getDescription() { @@ -34,11 +35,11 @@ public int getSize() { return size; } - public void setEmpty(boolean empty) { - isEmpty = empty; - } - - public boolean isEmpty() { - return isEmpty; + @Override + public String toString() { + String fileName = Paths.get(filePath).getFileName().toString(); + return "\n" + "название: " + fileName + + ", описание: " + description + + ", размер в мб: " + size; } } diff --git a/common/src/com/soroko/common/Message.java b/common/src/com/soroko/common/Message.java index 6bbc49a..19f5d9e 100644 --- a/common/src/com/soroko/common/Message.java +++ b/common/src/com/soroko/common/Message.java @@ -9,6 +9,7 @@ public class Message implements Serializable { private String sender; private String text; private String sentAt; + private boolean isEmpty; public Message(String sender) { this.sender = sender; @@ -37,4 +38,12 @@ public String getSentAt() { public void setSentAt(String sentAt) { this.sentAt = sentAt; } + + public void setEmpty(boolean empty) { + isEmpty = empty; + } + + public boolean isEmpty() { + return isEmpty; + } } diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 9bbee19..560f6ac 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -30,6 +30,7 @@ public class Server { private int amountOfSymbols; private int randomName; ArrayList files = new ArrayList<>(); + ArrayList fileMessages = new ArrayList<>(); public Server(int port) { this.port = port; @@ -39,10 +40,13 @@ public Server(int port) { public synchronized void showFiles() { Message message = new Message("server"); - String intro = "Список доступных файлов:" + "\n"; - String fileNames = files.stream().map(File::getName).collect(Collectors.joining(", ")); - if (files.isEmpty()) message.setText("Доступных файлов не обнаружено"); - else message.setText(intro + fileNames); + String intro = "Список доступных файлов:"; + String fileInformation = fileMessages.stream() + .map(FileMessage::toString).collect(Collectors.joining(", ")); + if (files.isEmpty()) { + // message.setEmpty(true); + message.setText("Доступных файлов не обнаружено"); + } else message.setText(intro + fileInformation); try { connectionHandler.send(message); } catch (IOException e) { @@ -53,7 +57,7 @@ public synchronized void showFiles() { public synchronized void loadFile(FileMessage fileMessage) { randomName = (int) (Math.random() * 1000); char[] descriptionChars = fileMessage.getDescription().toCharArray(); - File fileSource = new File(fileMessage.getFilepath()); + File fileSource = new File(fileMessage.getFilePath()); String fileName = SERVER_STORAGE_LOCATION + fileSource.getName(); String fileWasCreated; File fileDestination; @@ -68,8 +72,11 @@ public synchronized void loadFile(FileMessage fileMessage) { if (fileMessage.getSize() <= fileSize && descriptionChars.length <= amountOfSymbols) { try { copy(fileSource, fileDestination); - if (fileDestination.isFile()) + if (fileDestination.isFile()) { files.add(fileDestination); + fileMessage.setFilePath(fileDestination.getName()); + fileMessages.add(fileMessage); + } fileWasCreated = "Файл " + fileDestination.getName() + " был успешно загружен"; Message fileWasCreatedMessage = new Message("server"); fileWasCreatedMessage.setText(fileWasCreated); @@ -88,8 +95,8 @@ public synchronized void loadFile(FileMessage fileMessage) { Message fileDoesNotExistMsg = new Message("server"); fileDoesNotExistMsg.setText(fileDoesNotExist); try { - connectionHandler.send(fileDoesNotExistMsg); - } catch (IOException e) { + messages.put(fileDoesNotExistMsg); + } catch (InterruptedException e) { System.out.println(e.getMessage()); } } @@ -98,12 +105,12 @@ public synchronized void loadFile(FileMessage fileMessage) { synchronized void saveFile(FileMessage fileMessage) { File fileSource = new File((SERVER_STORAGE_LOCATION + fileMessage.getDescription())); - File fileDestination = new File(fileMessage.getFilepath() + fileMessage.getDescription()); + File fileDestination = new File(fileMessage.getFilePath() + fileMessage.getDescription()); String fileWasCreated; try { copy(fileSource, fileDestination); if (fileDestination.isFile()) { - fileWasCreated = "Файл " + fileDestination.getName() + " был успешно сохранен с сервера"; + fileWasCreated = "Файл " + fileDestination.getName() + " был успешно сохранен"; Message fileWasCreatedMessage = new Message("server"); fileWasCreatedMessage.setText(fileWasCreated); try { @@ -113,7 +120,14 @@ synchronized void saveFile(FileMessage fileMessage) { } } } catch (IOException e) { - throw new RuntimeException(e); + String fileWasNotCreated = "Неверное имя файла или файла нет в списке"; + Message fileWasNotCreatedMsg = new Message("server"); + fileWasNotCreatedMsg.setText(fileWasNotCreated); + try { + messages.put(fileWasNotCreatedMsg); + } catch (InterruptedException ex) { + System.out.println(ex.getMessage()); + } } } From 9a2608955a1afb2a2ffa941bb21f4ced0082dc66 Mon Sep 17 00:00:00 2001 From: maddojka Date: Sun, 5 May 2024 11:41:53 +0300 Subject: [PATCH 06/18] Server-client course work - minor changes --- common/src/com/soroko/common/FileMessage.java | 2 +- common/src/com/soroko/common/SendReceive.java | 1 - .../src/com/soroko/common/WriteMessage.java | 2 +- server/src/com/soroko/server/Server.java | 28 ++++++------------- 4 files changed, 11 insertions(+), 22 deletions(-) diff --git a/common/src/com/soroko/common/FileMessage.java b/common/src/com/soroko/common/FileMessage.java index f4f84e1..7c5fda1 100644 --- a/common/src/com/soroko/common/FileMessage.java +++ b/common/src/com/soroko/common/FileMessage.java @@ -38,7 +38,7 @@ public int getSize() { @Override public String toString() { String fileName = Paths.get(filePath).getFileName().toString(); - return "\n" + "название: " + fileName + + return "\n" + "название: " + fileName + ", описание: " + description + ", размер в мб: " + size; } diff --git a/common/src/com/soroko/common/SendReceive.java b/common/src/com/soroko/common/SendReceive.java index a69969c..5fe4b87 100644 --- a/common/src/com/soroko/common/SendReceive.java +++ b/common/src/com/soroko/common/SendReceive.java @@ -13,7 +13,6 @@ public class SendReceive implements AutoCloseable { private Socket socket; - public SendReceive(Socket socket) throws IOException { this.socket = Objects.requireNonNull(socket); outputStream = new ObjectOutputStream(socket.getOutputStream()); diff --git a/common/src/com/soroko/common/WriteMessage.java b/common/src/com/soroko/common/WriteMessage.java index 3b47349..205eace 100644 --- a/common/src/com/soroko/common/WriteMessage.java +++ b/common/src/com/soroko/common/WriteMessage.java @@ -20,7 +20,7 @@ public void run() { System.out.println("Введите имя"); username = scanner.nextLine(); - while(true) { + while (true) { System.out.println("Введите текст сообщения"); String text = scanner.nextLine(); if (text.equals("/exit")) break; diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 560f6ac..9e6e778 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -17,11 +17,9 @@ public class Server { - public static final String SERVER_STORAGE_LOCATION = - "C:\\Users\\yuriy\\IdeaProjects\\socketLesson\\server\\src\\com\\soroko\\server\\"; + public static final String SERVER_STORAGE_LOCATION = "C:\\Users\\yuriy\\IdeaProjects\\socketLesson\\server\\src\\com\\soroko\\server\\"; private final int port; - private final ArrayBlockingQueue messages = - new ArrayBlockingQueue<>(1000, true); + private final ArrayBlockingQueue messages = new ArrayBlockingQueue<>(1000, true); private final List connectionHandlers = new CopyOnWriteArrayList<>(); Sender sender; ThreadForClient threadForClient; @@ -41,8 +39,7 @@ public Server(int port) { public synchronized void showFiles() { Message message = new Message("server"); String intro = "Список доступных файлов:"; - String fileInformation = fileMessages.stream() - .map(FileMessage::toString).collect(Collectors.joining(", ")); + String fileInformation = fileMessages.stream().map(FileMessage::toString).collect(Collectors.joining(", ")); if (files.isEmpty()) { // message.setEmpty(true); message.setText("Доступных файлов не обнаружено"); @@ -63,8 +60,7 @@ public synchronized void loadFile(FileMessage fileMessage) { File fileDestination; Path path = Paths.get(fileName); if (Files.exists(path)) { - fileDestination = - new File((SERVER_STORAGE_LOCATION + randomName + fileSource.getName())); + fileDestination = new File((SERVER_STORAGE_LOCATION + randomName + fileSource.getName())); } else { fileDestination = new File(fileName); } @@ -90,8 +86,7 @@ public synchronized void loadFile(FileMessage fileMessage) { } } } else { - String fileDoesNotExist = "Файл по указанному пути не найден" + - " или содержит слишком большой объем информации"; + String fileDoesNotExist = "Файл по указанному пути не найден" + " или содержит слишком большой объем информации"; Message fileDoesNotExistMsg = new Message("server"); fileDoesNotExistMsg.setText(fileDoesNotExist); try { @@ -103,8 +98,7 @@ public synchronized void loadFile(FileMessage fileMessage) { } synchronized void saveFile(FileMessage fileMessage) { - File fileSource = - new File((SERVER_STORAGE_LOCATION + fileMessage.getDescription())); + File fileSource = new File((SERVER_STORAGE_LOCATION + fileMessage.getDescription())); File fileDestination = new File(fileMessage.getFilePath() + fileMessage.getDescription()); String fileWasCreated; try { @@ -185,12 +179,9 @@ public void run() { } catch (ClassNotFoundException e) { throw new RuntimeException(e); } - if (fromClient != null && !fromClient.getText().equals("/files") - && !fromClient.getText().equals("/loadfile") - && !fromClient.getText().equals("/savefile")) { + if (fromClient != null && !fromClient.getText().equals("/files") && !fromClient.getText().equals("/loadfile") && !fromClient.getText().equals("/savefile")) { Message message = new Message("server: " + fromClient.getSender()); - message.setText(fromClient.getSentAt() + " " - + fromClient.getSender() + ": " + fromClient.getText()); + message.setText(fromClient.getSentAt() + " " + fromClient.getSender() + ": " + fromClient.getText()); try { messages.put(message); } catch (InterruptedException e) { @@ -234,8 +225,7 @@ public void run() { Message message = messages.take(); for (SendReceive handler : connectionHandlers) { try { - if (handler != null) - handler.send(message); + if (handler != null) handler.send(message); } catch (IOException e) { connectionHandlers.remove(handler); } From d73419727f62282f16c036d7773ec260741bbf84 Mon Sep 17 00:00:00 2001 From: maddojka Date: Sun, 5 May 2024 13:25:52 +0300 Subject: [PATCH 07/18] Server-client course work - another update --- .gitignore | 29 ++++++++++++ .idea/.gitignore | 3 ++ .idea/misc.xml | 6 +++ .idea/modules.xml | 11 +++++ client/client.iml | 12 +++++ client/src/com/soroko/client/Client.java | 2 +- common/common.iml | 11 +++++ server/server.iml | 12 +++++ server/src/com/soroko/server/Server.java | 56 +++++++++++------------- 9 files changed, 111 insertions(+), 31 deletions(-) create mode 100644 .gitignore create mode 100644 .idea/.gitignore create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 client/client.iml create mode 100644 common/common.iml create mode 100644 server/server.iml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +### IntelliJ IDEA ### +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..6f29fee --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..0eb734f --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/client/client.iml b/client/client.iml new file mode 100644 index 0000000..99e828d --- /dev/null +++ b/client/client.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/client/src/com/soroko/client/Client.java b/client/src/com/soroko/client/Client.java index 6af10e8..1825c70 100644 --- a/client/src/com/soroko/client/Client.java +++ b/client/src/com/soroko/client/Client.java @@ -62,7 +62,7 @@ public void run() { } else if (isSaveCommand) { saveCommand(); isSaveCommand = false; - } else System.out.println("Введите текст сообщения"); + } else System.out.println("Введите текст сообщения"); String text = scanner.nextLine(); if (text.equalsIgnoreCase("/loadfile")) isLoadCommand = true; if (text.equalsIgnoreCase("/savefile")) isSaveCommand = true; diff --git a/common/common.iml b/common/common.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/common/common.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/server/server.iml b/server/server.iml new file mode 100644 index 0000000..99e828d --- /dev/null +++ b/server/server.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 9e6e778..1e02996 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -27,7 +27,6 @@ public class Server { private int fileSize; private int amountOfSymbols; private int randomName; - ArrayList files = new ArrayList<>(); ArrayList fileMessages = new ArrayList<>(); public Server(int port) { @@ -40,7 +39,7 @@ public synchronized void showFiles() { Message message = new Message("server"); String intro = "Список доступных файлов:"; String fileInformation = fileMessages.stream().map(FileMessage::toString).collect(Collectors.joining(", ")); - if (files.isEmpty()) { + if (fileMessages.isEmpty()) { // message.setEmpty(true); message.setText("Доступных файлов не обнаружено"); } else message.setText(intro + fileInformation); @@ -56,7 +55,7 @@ public synchronized void loadFile(FileMessage fileMessage) { char[] descriptionChars = fileMessage.getDescription().toCharArray(); File fileSource = new File(fileMessage.getFilePath()); String fileName = SERVER_STORAGE_LOCATION + fileSource.getName(); - String fileWasCreated; + String answer; File fileDestination; Path path = Paths.get(fileName); if (Files.exists(path)) { @@ -64,21 +63,21 @@ public synchronized void loadFile(FileMessage fileMessage) { } else { fileDestination = new File(fileName); } + Message message = new Message("server"); if (!fileSource.isDirectory() && fileSource.exists()) { if (fileMessage.getSize() <= fileSize && descriptionChars.length <= amountOfSymbols) { try { copy(fileSource, fileDestination); if (fileDestination.isFile()) { - files.add(fileDestination); fileMessage.setFilePath(fileDestination.getName()); fileMessages.add(fileMessage); } - fileWasCreated = "Файл " + fileDestination.getName() + " был успешно загружен"; - Message fileWasCreatedMessage = new Message("server"); - fileWasCreatedMessage.setText(fileWasCreated); + answer = "Файл " + fileDestination.getName() + " был успешно загружен"; + message.setText(answer); try { - messages.put(fileWasCreatedMessage); + messages.put(message); } catch (InterruptedException e) { + messages.remove(message); System.out.println(e.getMessage()); } } catch (IOException e) { @@ -86,13 +85,13 @@ public synchronized void loadFile(FileMessage fileMessage) { } } } else { - String fileDoesNotExist = "Файл по указанному пути не найден" + " или содержит слишком большой объем информации"; - Message fileDoesNotExistMsg = new Message("server"); - fileDoesNotExistMsg.setText(fileDoesNotExist); + answer = "Файл по указанному пути не найден" + + " или содержит слишком большой объем информации"; + message.setText(answer); try { - messages.put(fileDoesNotExistMsg); - } catch (InterruptedException e) { - System.out.println(e.getMessage()); + connectionHandler.send(message); + } catch (IOException e) { + connectionHandler.close(); } } } @@ -100,27 +99,22 @@ public synchronized void loadFile(FileMessage fileMessage) { synchronized void saveFile(FileMessage fileMessage) { File fileSource = new File((SERVER_STORAGE_LOCATION + fileMessage.getDescription())); File fileDestination = new File(fileMessage.getFilePath() + fileMessage.getDescription()); - String fileWasCreated; + String answer; + Message message = new Message("server"); try { copy(fileSource, fileDestination); if (fileDestination.isFile()) { - fileWasCreated = "Файл " + fileDestination.getName() + " был успешно сохранен"; - Message fileWasCreatedMessage = new Message("server"); - fileWasCreatedMessage.setText(fileWasCreated); - try { - messages.put(fileWasCreatedMessage); - } catch (InterruptedException e) { - System.out.println(e.getMessage()); - } + answer = "Файл " + fileDestination.getName() + " был успешно сохранен"; + message.setText(answer); + connectionHandler.send(message); } } catch (IOException e) { - String fileWasNotCreated = "Неверное имя файла или файла нет в списке"; - Message fileWasNotCreatedMsg = new Message("server"); - fileWasNotCreatedMsg.setText(fileWasNotCreated); + answer = "Неверное имя файла или файла нет в списке"; + message.setText(answer); try { - messages.put(fileWasNotCreatedMsg); - } catch (InterruptedException ex) { - System.out.println(ex.getMessage()); + connectionHandler.send(message); + } catch (IOException ex) { + connectionHandler.close(); } } } @@ -179,7 +173,9 @@ public void run() { } catch (ClassNotFoundException e) { throw new RuntimeException(e); } - if (fromClient != null && !fromClient.getText().equals("/files") && !fromClient.getText().equals("/loadfile") && !fromClient.getText().equals("/savefile")) { + if (fromClient != null && !fromClient.getText().equals("/files") && + !fromClient.getText().equals("/loadfile") && !fromClient.getText().equals("/savefile") && + !fromClient.getText().isEmpty()) { Message message = new Message("server: " + fromClient.getSender()); message.setText(fromClient.getSentAt() + " " + fromClient.getSender() + ": " + fromClient.getText()); try { From 08da77360188f54627fa6e30281c6a598e4dd5fe Mon Sep 17 00:00:00 2001 From: maddojka Date: Sun, 5 May 2024 20:16:00 +0300 Subject: [PATCH 08/18] Server-client course work - update --- client/src/com/soroko/client/Client.java | 20 +-- server/src/com/soroko/server/Server.java | 179 ++++++++++++++++++----- 2 files changed, 153 insertions(+), 46 deletions(-) diff --git a/client/src/com/soroko/client/Client.java b/client/src/com/soroko/client/Client.java index 1825c70..852ba2e 100644 --- a/client/src/com/soroko/client/Client.java +++ b/client/src/com/soroko/client/Client.java @@ -14,7 +14,6 @@ public class Client { private String username; private Scanner scanner; private SendReceive connectionHandler; - private boolean isEmpty; public Client(InetSocketAddress address) { this.address = address; @@ -22,10 +21,12 @@ public Client(InetSocketAddress address) { } public void saveCommand() { - System.out.println("Укажите папку, в которую необходимо загрузить файл из сервера"); - String filepath = scanner.nextLine(); - System.out.println("Введите название файла из списка доступных файлов:"); - String description = scanner.nextLine(); + String filepath = ""; + String description = ""; + System.out.println("Укажите папку, в которую необходимо загрузить файл из сервера"); + filepath = scanner.nextLine(); + System.out.println("Введите название файла из списка доступных файлов:"); + description = scanner.nextLine(); FileMessage fileMessage = new FileMessage(description, filepath); fileMessage.setFilePath(filepath); try { @@ -58,11 +59,13 @@ public void run() { while (true) { if (isLoadCommand) { loadCommand(); - isLoadCommand = false; + // isLoadCommand = false; } else if (isSaveCommand) { saveCommand(); - isSaveCommand = false; - } else System.out.println("Введите текст сообщения"); + // isSaveCommand = false; + } else System.out.println("Введите текст сообщения"); + isLoadCommand = false; + isSaveCommand = false; String text = scanner.nextLine(); if (text.equalsIgnoreCase("/loadfile")) isLoadCommand = true; if (text.equalsIgnoreCase("/savefile")) isSaveCommand = true; @@ -99,7 +102,6 @@ public void run() { throw new RuntimeException(e); } System.out.println(message.getText()); - if (message.isEmpty()) isEmpty = true; } } } diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 1e02996..8d2063d 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -8,7 +8,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.ArrayBlockingQueue; @@ -17,17 +16,18 @@ public class Server { - public static final String SERVER_STORAGE_LOCATION = "C:\\Users\\yuriy\\IdeaProjects\\socketLesson\\server\\src\\com\\soroko\\server\\"; + public static final String SERVER_STORAGE_LOCATION + = "C:\\Users\\yuriy\\IdeaProjects\\socketLesson\\server\\src\\com\\soroko\\server\\"; private final int port; private final ArrayBlockingQueue messages = new ArrayBlockingQueue<>(1000, true); private final List connectionHandlers = new CopyOnWriteArrayList<>(); + private final List fileMessages = new CopyOnWriteArrayList<>(); Sender sender; ThreadForClient threadForClient; SendReceive connectionHandler; - private int fileSize; - private int amountOfSymbols; - private int randomName; - ArrayList fileMessages = new ArrayList<>(); + private final int fileSize; + private final int amountOfSymbols; + public Server(int port) { this.port = port; @@ -35,23 +35,27 @@ public Server(int port) { amountOfSymbols = 200; } - public synchronized void showFiles() { + /* public synchronized void showFiles() { Message message = new Message("server"); String intro = "Список доступных файлов:"; - String fileInformation = fileMessages.stream().map(FileMessage::toString).collect(Collectors.joining(", ")); + String fileInformation = fileMessages.stream() + .map(FileMessage::toString) + .collect(Collectors.joining(", ")); if (fileMessages.isEmpty()) { - // message.setEmpty(true); + message.setEmpty(true); message.setText("Доступных файлов не обнаружено"); - } else message.setText(intro + fileInformation); + } else { + message.setText(intro + fileInformation); + } try { connectionHandler.send(message); } catch (IOException e) { connectionHandler.close(); } - } + }*/ - public synchronized void loadFile(FileMessage fileMessage) { - randomName = (int) (Math.random() * 1000); + /*public synchronized void loadFile(FileMessage fileMessage) { + int randomName = (int) (Math.random() * 1000); char[] descriptionChars = fileMessage.getDescription().toCharArray(); File fileSource = new File(fileMessage.getFilePath()); String fileName = SERVER_STORAGE_LOCATION + fileSource.getName(); @@ -71,13 +75,13 @@ public synchronized void loadFile(FileMessage fileMessage) { if (fileDestination.isFile()) { fileMessage.setFilePath(fileDestination.getName()); fileMessages.add(fileMessage); + message.setEmpty(false); } answer = "Файл " + fileDestination.getName() + " был успешно загружен"; message.setText(answer); try { messages.put(message); } catch (InterruptedException e) { - messages.remove(message); System.out.println(e.getMessage()); } } catch (IOException e) { @@ -94,9 +98,9 @@ public synchronized void loadFile(FileMessage fileMessage) { connectionHandler.close(); } } - } + }*/ - synchronized void saveFile(FileMessage fileMessage) { + /*synchronized void saveFile(FileMessage fileMessage) { File fileSource = new File((SERVER_STORAGE_LOCATION + fileMessage.getDescription())); File fileDestination = new File(fileMessage.getFilePath() + fileMessage.getDescription()); String answer; @@ -109,7 +113,8 @@ synchronized void saveFile(FileMessage fileMessage) { connectionHandler.send(message); } } catch (IOException e) { - answer = "Неверное имя файла или файла нет в списке"; + answer = "Неверное имя файла или файла нет в списке, " + + "либо файл с таким именем уже существует"; message.setText(answer); try { connectionHandler.send(message); @@ -117,7 +122,20 @@ synchronized void saveFile(FileMessage fileMessage) { connectionHandler.close(); } } - } + }*/ + + /*public FileMessage createFileMessage() { + FileMessage fileMessage; + try { + fileMessage = connectionHandler.receiveFileDescription(); + } catch (IOException e) { + connectionHandlers.remove(connectionHandler); + return null; + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + return fileMessage; + }*/ public void startServer() { try (ServerSocket serverSocket = new ServerSocket(port)) { @@ -129,6 +147,7 @@ public void startServer() { // SendReceive connectionHandler = new SendReceive(socket); connectionHandler = new SendReceive(socket); connectionHandlers.add(connectionHandler); + System.out.println(connectionHandler); threadForClient = new ThreadForClient(connectionHandler); threadForClient.start(); } catch (Exception e) { @@ -153,6 +172,108 @@ public ThreadForClient(SendReceive connectionHandler) { this.connectionHandler = connectionHandler; } + public synchronized void showFiles() { + Message message = new Message("server"); + String intro = "Список доступных файлов:"; + String fileInformation = fileMessages.stream() + .map(FileMessage::toString) + .collect(Collectors.joining(", ")); + if (fileMessages.isEmpty()) { + message.setEmpty(true); + message.setText("Доступных файлов не обнаружено"); + } else { + message.setText(intro + fileInformation); + } + try { + connectionHandler.send(message); + } catch (IOException e) { + connectionHandler.close(); + } + } + + public synchronized void loadFile(FileMessage fileMessage) { + int randomName = (int) (Math.random() * 1000); + char[] descriptionChars = fileMessage.getDescription().toCharArray(); + File fileSource = new File(fileMessage.getFilePath()); + String fileName = SERVER_STORAGE_LOCATION + fileSource.getName(); + String answer; + File fileDestination; + Path path = Paths.get(fileName); + if (Files.exists(path)) { + fileDestination = new File((SERVER_STORAGE_LOCATION + randomName + fileSource.getName())); + } else { + fileDestination = new File(fileName); + } + Message message = new Message("server"); + if (!fileSource.isDirectory() && fileSource.exists()) { + if (fileMessage.getSize() <= fileSize && descriptionChars.length <= amountOfSymbols) { + try { + copy(fileSource, fileDestination); + if (fileDestination.isFile()) { + fileMessage.setFilePath(fileDestination.getName()); + fileMessages.add(fileMessage); + message.setEmpty(false); + } + answer = "Файл " + fileDestination.getName() + " был успешно загружен"; + message.setText(answer); + try { + messages.put(message); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } else { + answer = "Файл по указанному пути не найден" + + " или содержит слишком большой объем информации"; + message.setText(answer); + try { + connectionHandler.send(message); + } catch (IOException e) { + connectionHandler.close(); + } + } + } + + synchronized void saveFile(FileMessage fileMessage) { + File fileSource = new File((SERVER_STORAGE_LOCATION + fileMessage.getDescription())); + File fileDestination = new File(fileMessage.getFilePath() + fileMessage.getDescription()); + String answer; + Message message = new Message("server"); + try { + copy(fileSource, fileDestination); + if (fileDestination.isFile()) { + answer = "Файл " + fileDestination.getName() + " был успешно сохранен"; + message.setText(answer); + connectionHandler.send(message); + } + } catch (IOException e) { + answer = "Неверное имя файла или файла нет в списке, " + + "либо файл с таким именем уже существует"; + message.setText(answer); + try { + connectionHandler.send(message); + } catch (IOException ex) { + connectionHandler.close(); + } + } + } + + public FileMessage createFileMessage() { + FileMessage fileMessage; + try { + fileMessage = connectionHandler.receiveFileDescription(); + } catch (IOException e) { + connectionHandlers.remove(connectionHandler); + return null; + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + return fileMessage; + } + public SendReceive getConnectionHandler() { return connectionHandler; } @@ -186,27 +307,11 @@ public void run() { } else if (Objects.requireNonNull(fromClient).getText().equals("/files")) { showFiles(); } else if (fromClient.getText().equals("/loadfile")) { - FileMessage fileMessage; - try { - fileMessage = connectionHandler.receiveFileDescription(); - } catch (IOException e) { - connectionHandlers.remove(connectionHandler); - return; - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } + FileMessage fileMessage = createFileMessage(); loadFile(fileMessage); } else if (fromClient.getText().equals("/savefile")) { showFiles(); - FileMessage fileMessage; - try { - fileMessage = connectionHandler.receiveFileDescription(); - } catch (IOException e) { - connectionHandlers.remove(connectionHandler); - return; - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } + FileMessage fileMessage = createFileMessage(); saveFile(fileMessage); } } @@ -216,7 +321,7 @@ public void run() { private class Sender extends Thread { @Override public void run() { - while (!Thread.currentThread().isInterrupted()) { // true + while (!Thread.currentThread().isInterrupted()) { try { Message message = messages.take(); for (SendReceive handler : connectionHandlers) { From 4900491c2fdbf34a6cf622fa83227539c3e53ac6 Mon Sep 17 00:00:00 2001 From: maddojka Date: Sun, 5 May 2024 20:18:00 +0300 Subject: [PATCH 09/18] Server-client course work - update --- server/src/com/soroko/server/Server.java | 109 +---------------------- 1 file changed, 3 insertions(+), 106 deletions(-) diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 8d2063d..33e6fd5 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -22,121 +22,18 @@ public class Server { private final ArrayBlockingQueue messages = new ArrayBlockingQueue<>(1000, true); private final List connectionHandlers = new CopyOnWriteArrayList<>(); private final List fileMessages = new CopyOnWriteArrayList<>(); - Sender sender; - ThreadForClient threadForClient; - SendReceive connectionHandler; + private Sender sender; + private ThreadForClient threadForClient; + private SendReceive connectionHandler; private final int fileSize; private final int amountOfSymbols; - public Server(int port) { this.port = port; fileSize = 10; amountOfSymbols = 200; } - /* public synchronized void showFiles() { - Message message = new Message("server"); - String intro = "Список доступных файлов:"; - String fileInformation = fileMessages.stream() - .map(FileMessage::toString) - .collect(Collectors.joining(", ")); - if (fileMessages.isEmpty()) { - message.setEmpty(true); - message.setText("Доступных файлов не обнаружено"); - } else { - message.setText(intro + fileInformation); - } - try { - connectionHandler.send(message); - } catch (IOException e) { - connectionHandler.close(); - } - }*/ - - /*public synchronized void loadFile(FileMessage fileMessage) { - int randomName = (int) (Math.random() * 1000); - char[] descriptionChars = fileMessage.getDescription().toCharArray(); - File fileSource = new File(fileMessage.getFilePath()); - String fileName = SERVER_STORAGE_LOCATION + fileSource.getName(); - String answer; - File fileDestination; - Path path = Paths.get(fileName); - if (Files.exists(path)) { - fileDestination = new File((SERVER_STORAGE_LOCATION + randomName + fileSource.getName())); - } else { - fileDestination = new File(fileName); - } - Message message = new Message("server"); - if (!fileSource.isDirectory() && fileSource.exists()) { - if (fileMessage.getSize() <= fileSize && descriptionChars.length <= amountOfSymbols) { - try { - copy(fileSource, fileDestination); - if (fileDestination.isFile()) { - fileMessage.setFilePath(fileDestination.getName()); - fileMessages.add(fileMessage); - message.setEmpty(false); - } - answer = "Файл " + fileDestination.getName() + " был успешно загружен"; - message.setText(answer); - try { - messages.put(message); - } catch (InterruptedException e) { - System.out.println(e.getMessage()); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } else { - answer = "Файл по указанному пути не найден" - + " или содержит слишком большой объем информации"; - message.setText(answer); - try { - connectionHandler.send(message); - } catch (IOException e) { - connectionHandler.close(); - } - } - }*/ - - /*synchronized void saveFile(FileMessage fileMessage) { - File fileSource = new File((SERVER_STORAGE_LOCATION + fileMessage.getDescription())); - File fileDestination = new File(fileMessage.getFilePath() + fileMessage.getDescription()); - String answer; - Message message = new Message("server"); - try { - copy(fileSource, fileDestination); - if (fileDestination.isFile()) { - answer = "Файл " + fileDestination.getName() + " был успешно сохранен"; - message.setText(answer); - connectionHandler.send(message); - } - } catch (IOException e) { - answer = "Неверное имя файла или файла нет в списке, " + - "либо файл с таким именем уже существует"; - message.setText(answer); - try { - connectionHandler.send(message); - } catch (IOException ex) { - connectionHandler.close(); - } - } - }*/ - - /*public FileMessage createFileMessage() { - FileMessage fileMessage; - try { - fileMessage = connectionHandler.receiveFileDescription(); - } catch (IOException e) { - connectionHandlers.remove(connectionHandler); - return null; - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - return fileMessage; - }*/ - public void startServer() { try (ServerSocket serverSocket = new ServerSocket(port)) { sender = new Sender(); From fed220e47d908e0c5ca6a717cfe6a80d88b94d03 Mon Sep 17 00:00:00 2001 From: maddojka Date: Mon, 6 May 2024 11:33:28 +0300 Subject: [PATCH 10/18] Server-client course work - update --- client/src/com/soroko/client/Client.java | 12 ++--- common/src/com/soroko/common/FileMessage.java | 9 ++++ common/src/com/soroko/common/Message.java | 15 ------ common/src/com/soroko/common/SendReceive.java | 8 ++++ server/src/com/soroko/server/Server.java | 46 ++++++++----------- 5 files changed, 41 insertions(+), 49 deletions(-) diff --git a/client/src/com/soroko/client/Client.java b/client/src/com/soroko/client/Client.java index 852ba2e..b5ba736 100644 --- a/client/src/com/soroko/client/Client.java +++ b/client/src/com/soroko/client/Client.java @@ -21,12 +21,10 @@ public Client(InetSocketAddress address) { } public void saveCommand() { - String filepath = ""; - String description = ""; - System.out.println("Укажите папку, в которую необходимо загрузить файл из сервера"); - filepath = scanner.nextLine(); - System.out.println("Введите название файла из списка доступных файлов:"); - description = scanner.nextLine(); + System.out.println("Укажите папку, в которую необходимо загрузить файл из сервера"); + String filepath = scanner.nextLine(); + System.out.println("Введите название файла из списка доступных файлов:"); + String description = scanner.nextLine(); FileMessage fileMessage = new FileMessage(description, filepath); fileMessage.setFilePath(filepath); try { @@ -59,10 +57,8 @@ public void run() { while (true) { if (isLoadCommand) { loadCommand(); - // isLoadCommand = false; } else if (isSaveCommand) { saveCommand(); - // isSaveCommand = false; } else System.out.println("Введите текст сообщения"); isLoadCommand = false; isSaveCommand = false; diff --git a/common/src/com/soroko/common/FileMessage.java b/common/src/com/soroko/common/FileMessage.java index 7c5fda1..d7ca6a5 100644 --- a/common/src/com/soroko/common/FileMessage.java +++ b/common/src/com/soroko/common/FileMessage.java @@ -7,6 +7,7 @@ public class FileMessage implements Serializable { private String description; private int size; private String filePath; + private boolean FilesAreEmpty; public FileMessage(String description, String filepath) { @@ -35,6 +36,14 @@ public int getSize() { return size; } + public boolean isFilesAreEmpty() { + return FilesAreEmpty; + } + + public void setFilesAreEmpty(boolean filesAreEmpty) { + FilesAreEmpty = filesAreEmpty; + } + @Override public String toString() { String fileName = Paths.get(filePath).getFileName().toString(); diff --git a/common/src/com/soroko/common/Message.java b/common/src/com/soroko/common/Message.java index 19f5d9e..b23f3d1 100644 --- a/common/src/com/soroko/common/Message.java +++ b/common/src/com/soroko/common/Message.java @@ -1,15 +1,11 @@ package com.soroko.common; import java.io.Serializable; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; public class Message implements Serializable { private String sender; private String text; private String sentAt; - private boolean isEmpty; public Message(String sender) { this.sender = sender; @@ -19,10 +15,6 @@ public String getSender() { return sender; } - public void setSender(String sender) { - this.sender = sender; - } - public String getText() { return text; } @@ -39,11 +31,4 @@ public void setSentAt(String sentAt) { this.sentAt = sentAt; } - public void setEmpty(boolean empty) { - isEmpty = empty; - } - - public boolean isEmpty() { - return isEmpty; - } } diff --git a/common/src/com/soroko/common/SendReceive.java b/common/src/com/soroko/common/SendReceive.java index 5fe4b87..b9e8b1e 100644 --- a/common/src/com/soroko/common/SendReceive.java +++ b/common/src/com/soroko/common/SendReceive.java @@ -11,6 +11,7 @@ public class SendReceive implements AutoCloseable { private ObjectOutputStream outputStream; private ObjectInputStream inputStream; private Socket socket; + private int id; public SendReceive(Socket socket) throws IOException { @@ -19,6 +20,13 @@ public SendReceive(Socket socket) throws IOException { inputStream = new ObjectInputStream(socket.getInputStream()); } + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } public void send(Message message) throws IOException { DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("HH:mm:ss"); diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 33e6fd5..1be6ed9 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -22,11 +22,9 @@ public class Server { private final ArrayBlockingQueue messages = new ArrayBlockingQueue<>(1000, true); private final List connectionHandlers = new CopyOnWriteArrayList<>(); private final List fileMessages = new CopyOnWriteArrayList<>(); - private Sender sender; - private ThreadForClient threadForClient; - private SendReceive connectionHandler; private final int fileSize; private final int amountOfSymbols; + private int count = 0; public Server(int port) { this.port = port; @@ -36,17 +34,15 @@ public Server(int port) { public void startServer() { try (ServerSocket serverSocket = new ServerSocket(port)) { - sender = new Sender(); - sender.start(); + new Sender().start(); while (true) { try { Socket socket = serverSocket.accept(); - // SendReceive connectionHandler = new SendReceive(socket); - connectionHandler = new SendReceive(socket); + SendReceive connectionHandler = new SendReceive(socket); + connectionHandler.setId(++count); + System.out.println(connectionHandler.getId()); connectionHandlers.add(connectionHandler); - System.out.println(connectionHandler); - threadForClient = new ThreadForClient(connectionHandler); - threadForClient.start(); + new ThreadForClient(connectionHandler).start(); } catch (Exception e) { System.out.println("Проблема с установкой нового соединения"); } @@ -63,7 +59,7 @@ public static void copy(File source, File dest) throws IOException { private class ThreadForClient extends Thread { private final SendReceive connectionHandler; - Message fromClient; + private Message fromClient; public ThreadForClient(SendReceive connectionHandler) { this.connectionHandler = connectionHandler; @@ -76,8 +72,7 @@ public synchronized void showFiles() { .map(FileMessage::toString) .collect(Collectors.joining(", ")); if (fileMessages.isEmpty()) { - message.setEmpty(true); - message.setText("Доступных файлов не обнаружено"); + message.setText("Доступных для скачивания файлов не обнаружено"); } else { message.setText(intro + fileInformation); } @@ -109,7 +104,6 @@ public synchronized void loadFile(FileMessage fileMessage) { if (fileDestination.isFile()) { fileMessage.setFilePath(fileDestination.getName()); fileMessages.add(fileMessage); - message.setEmpty(false); } answer = "Файл " + fileDestination.getName() + " был успешно загружен"; message.setText(answer); @@ -171,13 +165,6 @@ public FileMessage createFileMessage() { return fileMessage; } - public SendReceive getConnectionHandler() { - return connectionHandler; - } - - public Message getFromClient() { - return fromClient; - } @Override public void run() { @@ -205,17 +192,23 @@ public void run() { showFiles(); } else if (fromClient.getText().equals("/loadfile")) { FileMessage fileMessage = createFileMessage(); - loadFile(fileMessage); + loadFile(Objects.requireNonNull(fileMessage)); } else if (fromClient.getText().equals("/savefile")) { - showFiles(); - FileMessage fileMessage = createFileMessage(); - saveFile(fileMessage); + if (!fileMessages.isEmpty()) { + showFiles(); + } + FileMessage fileMessage = createFileMessage(); + fileMessage.setFilesAreEmpty(false); + saveFile(Objects.requireNonNull(fileMessage)); + } } } } private class Sender extends Thread { + private ThreadForClient threadForClient; + @Override public void run() { while (!Thread.currentThread().isInterrupted()) { @@ -223,7 +216,8 @@ public void run() { Message message = messages.take(); for (SendReceive handler : connectionHandlers) { try { - if (handler != null) handler.send(message); + if (handler != null) + handler.send(message); } catch (IOException e) { connectionHandlers.remove(handler); } From 25a993ba5a76539f8a56d17330f4669fa32be820 Mon Sep 17 00:00:00 2001 From: maddojka Date: Mon, 6 May 2024 13:35:16 +0300 Subject: [PATCH 11/18] Server-client course work - update --- client/src/com/soroko/client/Client.java | 22 ++++++++++++++----- common/src/com/soroko/common/FileMessage.java | 10 +-------- common/src/com/soroko/common/Message.java | 8 +++++++ server/src/com/soroko/server/Server.java | 9 ++++---- 4 files changed, 29 insertions(+), 20 deletions(-) diff --git a/client/src/com/soroko/client/Client.java b/client/src/com/soroko/client/Client.java index b5ba736..e37e045 100644 --- a/client/src/com/soroko/client/Client.java +++ b/client/src/com/soroko/client/Client.java @@ -14,17 +14,22 @@ public class Client { private String username; private Scanner scanner; private SendReceive connectionHandler; + private boolean FilesAreEmpty; public Client(InetSocketAddress address) { this.address = address; scanner = new Scanner(System.in); } - public void saveCommand() { - System.out.println("Укажите папку, в которую необходимо загрузить файл из сервера"); - String filepath = scanner.nextLine(); - System.out.println("Введите название файла из списка доступных файлов:"); - String description = scanner.nextLine(); + public void saveCommand() throws InterruptedException { + String filepath = ""; + String description = ""; + if (!FilesAreEmpty) { + System.out.println("Укажите папку, в которую необходимо загрузить файл из сервера"); + filepath = scanner.nextLine(); + System.out.println("Введите название файла из списка доступных файлов:"); + description = scanner.nextLine(); + } FileMessage fileMessage = new FileMessage(description, filepath); fileMessage.setFilePath(filepath); try { @@ -58,7 +63,11 @@ public void run() { if (isLoadCommand) { loadCommand(); } else if (isSaveCommand) { - saveCommand(); + try { + saveCommand(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } } else System.out.println("Введите текст сообщения"); isLoadCommand = false; isSaveCommand = false; @@ -87,6 +96,7 @@ public void run() { Message message; try { message = connectionHandler.receive(); + FilesAreEmpty = message.getFilesAreEmpty(); if (message.getText().equalsIgnoreCase("/exit")) { connectionHandler.close(); break; diff --git a/common/src/com/soroko/common/FileMessage.java b/common/src/com/soroko/common/FileMessage.java index d7ca6a5..409554b 100644 --- a/common/src/com/soroko/common/FileMessage.java +++ b/common/src/com/soroko/common/FileMessage.java @@ -7,7 +7,7 @@ public class FileMessage implements Serializable { private String description; private int size; private String filePath; - private boolean FilesAreEmpty; + public FileMessage(String description, String filepath) { @@ -36,14 +36,6 @@ public int getSize() { return size; } - public boolean isFilesAreEmpty() { - return FilesAreEmpty; - } - - public void setFilesAreEmpty(boolean filesAreEmpty) { - FilesAreEmpty = filesAreEmpty; - } - @Override public String toString() { String fileName = Paths.get(filePath).getFileName().toString(); diff --git a/common/src/com/soroko/common/Message.java b/common/src/com/soroko/common/Message.java index b23f3d1..b18f7ce 100644 --- a/common/src/com/soroko/common/Message.java +++ b/common/src/com/soroko/common/Message.java @@ -6,6 +6,7 @@ public class Message implements Serializable { private String sender; private String text; private String sentAt; + private boolean FilesAreEmpty; public Message(String sender) { this.sender = sender; @@ -31,4 +32,11 @@ public void setSentAt(String sentAt) { this.sentAt = sentAt; } + public boolean getFilesAreEmpty() { + return FilesAreEmpty; + } + + public void setFilesAreEmpty(boolean filesAreEmpty) { + FilesAreEmpty = filesAreEmpty; + } } diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 1be6ed9..6ad1f6c 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -72,6 +72,7 @@ public synchronized void showFiles() { .map(FileMessage::toString) .collect(Collectors.joining(", ")); if (fileMessages.isEmpty()) { + message.setFilesAreEmpty(true); message.setText("Доступных для скачивания файлов не обнаружено"); } else { message.setText(intro + fileInformation); @@ -104,6 +105,7 @@ public synchronized void loadFile(FileMessage fileMessage) { if (fileDestination.isFile()) { fileMessage.setFilePath(fileDestination.getName()); fileMessages.add(fileMessage); + message.setFilesAreEmpty(false); } answer = "Файл " + fileDestination.getName() + " был успешно загружен"; message.setText(answer); @@ -133,6 +135,7 @@ synchronized void saveFile(FileMessage fileMessage) { File fileDestination = new File(fileMessage.getFilePath() + fileMessage.getDescription()); String answer; Message message = new Message("server"); + if (fileMessages.isEmpty()) message.setFilesAreEmpty(true); try { copy(fileSource, fileDestination); if (fileDestination.isFile()) { @@ -188,19 +191,15 @@ public void run() { } catch (InterruptedException e) { System.out.println(e.getMessage()); } - } else if (Objects.requireNonNull(fromClient).getText().equals("/files")) { + } else if (fromClient.getText().equals("/files")) { showFiles(); } else if (fromClient.getText().equals("/loadfile")) { FileMessage fileMessage = createFileMessage(); loadFile(Objects.requireNonNull(fileMessage)); } else if (fromClient.getText().equals("/savefile")) { - if (!fileMessages.isEmpty()) { showFiles(); - } FileMessage fileMessage = createFileMessage(); - fileMessage.setFilesAreEmpty(false); saveFile(Objects.requireNonNull(fileMessage)); - } } } From 6f3fcff763fe1035f795763a424af06d6679aef1 Mon Sep 17 00:00:00 2001 From: maddojka Date: Mon, 6 May 2024 15:54:22 +0300 Subject: [PATCH 12/18] Server-client course work - update without sender --- common/src/com/soroko/common/SendReceive.java | 10 --- server/src/com/soroko/server/Server.java | 85 ++++++++----------- 2 files changed, 36 insertions(+), 59 deletions(-) diff --git a/common/src/com/soroko/common/SendReceive.java b/common/src/com/soroko/common/SendReceive.java index b9e8b1e..b522159 100644 --- a/common/src/com/soroko/common/SendReceive.java +++ b/common/src/com/soroko/common/SendReceive.java @@ -11,8 +11,6 @@ public class SendReceive implements AutoCloseable { private ObjectOutputStream outputStream; private ObjectInputStream inputStream; private Socket socket; - private int id; - public SendReceive(Socket socket) throws IOException { this.socket = Objects.requireNonNull(socket); @@ -20,14 +18,6 @@ public SendReceive(Socket socket) throws IOException { inputStream = new ObjectInputStream(socket.getInputStream()); } - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - public void send(Message message) throws IOException { DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("HH:mm:ss"); LocalTime localTime = LocalTime.now(); diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 6ad1f6c..8502f1f 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -10,7 +10,6 @@ import java.nio.file.Paths; import java.util.List; import java.util.Objects; -import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; @@ -19,12 +18,12 @@ public class Server { public static final String SERVER_STORAGE_LOCATION = "C:\\Users\\yuriy\\IdeaProjects\\socketLesson\\server\\src\\com\\soroko\\server\\"; private final int port; - private final ArrayBlockingQueue messages = new ArrayBlockingQueue<>(1000, true); + private final List messages = new CopyOnWriteArrayList<>(); private final List connectionHandlers = new CopyOnWriteArrayList<>(); + private final List threadForClients = new CopyOnWriteArrayList<>(); private final List fileMessages = new CopyOnWriteArrayList<>(); private final int fileSize; private final int amountOfSymbols; - private int count = 0; public Server(int port) { this.port = port; @@ -34,15 +33,14 @@ public Server(int port) { public void startServer() { try (ServerSocket serverSocket = new ServerSocket(port)) { - new Sender().start(); while (true) { try { Socket socket = serverSocket.accept(); SendReceive connectionHandler = new SendReceive(socket); - connectionHandler.setId(++count); - System.out.println(connectionHandler.getId()); connectionHandlers.add(connectionHandler); - new ThreadForClient(connectionHandler).start(); + ThreadForClient threadForClient = new ThreadForClient(connectionHandler); + threadForClient.start(); + threadForClients.add(threadForClient); } catch (Exception e) { System.out.println("Проблема с установкой нового соединения"); } @@ -53,18 +51,23 @@ public void startServer() { } } - public static void copy(File source, File dest) throws IOException { - Files.copy(source.toPath(), dest.toPath()); + public static void copy(File source, File destination) throws IOException { + Files.copy(source.toPath(), destination.toPath()); } private class ThreadForClient extends Thread { - private final SendReceive connectionHandler; - private Message fromClient; + final SendReceive connectionHandler; + private boolean selfMessageIsActive; + private boolean loadFileFlag; public ThreadForClient(SendReceive connectionHandler) { this.connectionHandler = connectionHandler; } + public SendReceive getConnectionHandler() { + return connectionHandler; + } + public synchronized void showFiles() { Message message = new Message("server"); String intro = "Список доступных файлов:"; @@ -109,11 +112,8 @@ public synchronized void loadFile(FileMessage fileMessage) { } answer = "Файл " + fileDestination.getName() + " был успешно загружен"; message.setText(answer); - try { - messages.put(message); - } catch (InterruptedException e) { - System.out.println(e.getMessage()); - } + loadFileFlag = true; + messages.add(message); } catch (IOException e) { throw new RuntimeException(e); } @@ -168,11 +168,10 @@ public FileMessage createFileMessage() { return fileMessage; } - @Override public void run() { while (true) { - fromClient = null; + Message fromClient; try { fromClient = connectionHandler.receive(); } catch (IOException e) { @@ -186,46 +185,34 @@ public void run() { !fromClient.getText().isEmpty()) { Message message = new Message("server: " + fromClient.getSender()); message.setText(fromClient.getSentAt() + " " + fromClient.getSender() + ": " + fromClient.getText()); - try { - messages.put(message); - } catch (InterruptedException e) { - System.out.println(e.getMessage()); - } - } else if (fromClient.getText().equals("/files")) { + messages.add(message); + } else if (Objects.requireNonNull(fromClient).getText().equals("/files")) { + selfMessageIsActive = true; showFiles(); } else if (fromClient.getText().equals("/loadfile")) { + selfMessageIsActive = true; FileMessage fileMessage = createFileMessage(); loadFile(Objects.requireNonNull(fileMessage)); } else if (fromClient.getText().equals("/savefile")) { - showFiles(); - FileMessage fileMessage = createFileMessage(); - saveFile(Objects.requireNonNull(fileMessage)); + selfMessageIsActive = true; + showFiles(); + FileMessage fileMessage = createFileMessage(); + saveFile(Objects.requireNonNull(fileMessage)); } - } - } - } - - private class Sender extends Thread { - private ThreadForClient threadForClient; - - @Override - public void run() { - while (!Thread.currentThread().isInterrupted()) { - try { - Message message = messages.take(); - for (SendReceive handler : connectionHandlers) { - try { - if (handler != null) - handler.send(message); - } catch (IOException e) { - connectionHandlers.remove(handler); + Message message = null; + if (!messages.isEmpty()) message = messages.getLast(); + for (SendReceive handler : connectionHandlers) { + try { + if ((handler != this.connectionHandler && !selfMessageIsActive) || loadFileFlag) { + handler.send(Objects.requireNonNull(message)); } - } - } catch (InterruptedException e) { - System.out.println(e.getMessage()); - Thread.currentThread().interrupt(); + } catch (IOException e) { + connectionHandlers.remove(handler); + } } + selfMessageIsActive = false; + loadFileFlag = false; } } } From 2638f94dd9284752242d5ede39784db00468b536 Mon Sep 17 00:00:00 2001 From: maddojka Date: Mon, 6 May 2024 21:58:14 +0300 Subject: [PATCH 13/18] Server-client course work - release --- common/src/com/soroko/common/FileMessage.java | 1 - server/src/com/soroko/server/Server.java | 10 ++++------ 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/common/src/com/soroko/common/FileMessage.java b/common/src/com/soroko/common/FileMessage.java index 409554b..7c5fda1 100644 --- a/common/src/com/soroko/common/FileMessage.java +++ b/common/src/com/soroko/common/FileMessage.java @@ -9,7 +9,6 @@ public class FileMessage implements Serializable { private String filePath; - public FileMessage(String description, String filepath) { this.description = description; this.filePath = filepath; diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 8502f1f..06ca87a 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -64,10 +64,6 @@ public ThreadForClient(SendReceive connectionHandler) { this.connectionHandler = connectionHandler; } - public SendReceive getConnectionHandler() { - return connectionHandler; - } - public synchronized void showFiles() { Message message = new Message("server"); String intro = "Список доступных файлов:"; @@ -113,6 +109,7 @@ public synchronized void loadFile(FileMessage fileMessage) { answer = "Файл " + fileDestination.getName() + " был успешно загружен"; message.setText(answer); loadFileFlag = true; + selfMessageIsActive = true; messages.add(message); } catch (IOException e) { throw new RuntimeException(e); @@ -186,6 +183,7 @@ public void run() { Message message = new Message("server: " + fromClient.getSender()); message.setText(fromClient.getSentAt() + " " + fromClient.getSender() + ": " + fromClient.getText()); messages.add(message); + System.out.println(messages); } else if (Objects.requireNonNull(fromClient).getText().equals("/files")) { selfMessageIsActive = true; showFiles(); @@ -203,10 +201,10 @@ public void run() { if (!messages.isEmpty()) message = messages.getLast(); for (SendReceive handler : connectionHandlers) { try { - if ((handler != this.connectionHandler && !selfMessageIsActive) || loadFileFlag) { + if ((handler != this.connectionHandler && !selfMessageIsActive) || + (handler == this.connectionHandler && this.loadFileFlag)) { handler.send(Objects.requireNonNull(message)); } - } catch (IOException e) { connectionHandlers.remove(handler); } From 06f48afb2ba82ab30f27e38af3c28b74e5814e38 Mon Sep 17 00:00:00 2001 From: maddojka Date: Tue, 7 May 2024 08:04:56 +0300 Subject: [PATCH 14/18] Server-client course work - release --- common/src/com/soroko/common/WriteMessage.java | 2 +- server/src/com/soroko/server/Server.java | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/common/src/com/soroko/common/WriteMessage.java b/common/src/com/soroko/common/WriteMessage.java index 205eace..faa31e6 100644 --- a/common/src/com/soroko/common/WriteMessage.java +++ b/common/src/com/soroko/common/WriteMessage.java @@ -4,7 +4,7 @@ import java.util.Scanner; public class WriteMessage extends Thread { - SendReceive connectionHandler; + private SendReceive connectionHandler; private String username; private Scanner scanner; private int counter; diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index 06ca87a..efaaf2a 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -56,7 +56,7 @@ public static void copy(File source, File destination) throws IOException { } private class ThreadForClient extends Thread { - final SendReceive connectionHandler; + private final SendReceive connectionHandler; private boolean selfMessageIsActive; private boolean loadFileFlag; @@ -183,7 +183,6 @@ public void run() { Message message = new Message("server: " + fromClient.getSender()); message.setText(fromClient.getSentAt() + " " + fromClient.getSender() + ": " + fromClient.getText()); messages.add(message); - System.out.println(messages); } else if (Objects.requireNonNull(fromClient).getText().equals("/files")) { selfMessageIsActive = true; showFiles(); From 97868ca52b1d377faca5f55e67500a08e5ca3ee7 Mon Sep 17 00:00:00 2001 From: maddojka Date: Tue, 7 May 2024 08:08:39 +0300 Subject: [PATCH 15/18] Server-client course work - release --- server/src/com/soroko/server/Server.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index efaaf2a..ae93902 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -20,7 +20,6 @@ public class Server { private final int port; private final List messages = new CopyOnWriteArrayList<>(); private final List connectionHandlers = new CopyOnWriteArrayList<>(); - private final List threadForClients = new CopyOnWriteArrayList<>(); private final List fileMessages = new CopyOnWriteArrayList<>(); private final int fileSize; private final int amountOfSymbols; @@ -38,9 +37,7 @@ public void startServer() { Socket socket = serverSocket.accept(); SendReceive connectionHandler = new SendReceive(socket); connectionHandlers.add(connectionHandler); - ThreadForClient threadForClient = new ThreadForClient(connectionHandler); - threadForClient.start(); - threadForClients.add(threadForClient); + new ThreadForClient(connectionHandler).start(); } catch (Exception e) { System.out.println("Проблема с установкой нового соединения"); } From 7be7e5ebaed9d5a454ea658ee1e1e012d7cef1f5 Mon Sep 17 00:00:00 2001 From: maddojka Date: Sat, 18 May 2024 11:40:52 +0300 Subject: [PATCH 16/18] Server-client course work - release --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index f68d109..4a601a1 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ out/ !**/src/main/**/out/ !**/src/test/**/out/ +.idea ### Eclipse ### .apt_generated From 326816e68503a0f0b39cc487b694cff17bb5c50e Mon Sep 17 00:00:00 2001 From: maddojka Date: Sat, 18 May 2024 11:41:17 +0300 Subject: [PATCH 17/18] Server-client course work - release --- server/src/com/soroko/server/Server.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/com/soroko/server/Server.java b/server/src/com/soroko/server/Server.java index ae93902..fc88f2a 100644 --- a/server/src/com/soroko/server/Server.java +++ b/server/src/com/soroko/server/Server.java @@ -197,7 +197,7 @@ public void run() { if (!messages.isEmpty()) message = messages.getLast(); for (SendReceive handler : connectionHandlers) { try { - if ((handler != this.connectionHandler && !selfMessageIsActive) || + if ((handler != this.connectionHandler && !this.selfMessageIsActive) || (handler == this.connectionHandler && this.loadFileFlag)) { handler.send(Objects.requireNonNull(message)); } From c1d16456a76b6b957fda522f59153a7f86f67380 Mon Sep 17 00:00:00 2001 From: Yuriy Soroko <117828176+maddojka@users.noreply.github.com> Date: Sat, 18 May 2024 11:42:04 +0300 Subject: [PATCH 18/18] Delete .idea directory --- .idea/.gitignore | 3 --- .idea/misc.xml | 6 ------ .idea/modules.xml | 11 ----------- 3 files changed, 20 deletions(-) delete mode 100644 .idea/.gitignore delete mode 100644 .idea/misc.xml delete mode 100644 .idea/modules.xml diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 26d3352..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 6f29fee..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 0eb734f..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file