The application must send the file from the client to the server. But it hangs in the read cycle on the server side. Please help me find the problem, otherwise I’m completely sulked by something ... Here’s the code:
Server:
public class Server { public static void main(String[] args) { Server server = new Server(); server.initServerSocket(); server.initSocket(); server.download("root.txt"); } private ServerSocket serverSocket; private Socket socket; private void initServerSocket() { try { this.serverSocket = new ServerSocket(5213); } catch (IOException e) { e.printStackTrace(); } } private void initSocket() { try { this.socket = this.serverSocket.accept(); } catch (IOException e) { e.printStackTrace(); } } private void download(String nameFile) { try (InputStream input = this.socket.getInputStream()){ // available() - возвращает колличество сейчас доступных байтов byte[] buffer = new byte[input.available()]; // читаем int i = input.read(buffer); while (i != -1) { System.out.println("1.6"); // ВОТ ТУТ НЕ ВЫХОДИТ ИЗ ЦИКЛА i = input.read(buffer); } this.createFile(nameFile,buffer); } catch (IOException e) { e.printStackTrace(); } } private boolean createFile(String nameFile, byte[] buffer) { File file = new File(format("%s/%s",Paths.REPO.getPath(),nameFile)); if (!file.exists()) { try (OutputStream out = new FileOutputStream(file)) { System.out.println("1.8"); out.write(buffer); } catch (IOException e) { e.printStackTrace(); } } return file.exists(); } } And here is the client:
public class Client { public static void main(String[] args) { int port = 5213; String address = "127.0.0.1"; Client client = new Client(); client.initSocket(address,port); client.upload("/Users/pavel/Desktop/test/client/root.txt"); } private Socket socket; private void initSocket(String address, int port) { try { this.socket = new Socket(address, port); } catch (IOException e) { e.printStackTrace(); } } private void upload(String path) { try (OutputStream out = this.socket.getOutputStream(); FileInputStream fileIn = new FileInputStream(new File(path)); BufferedInputStream buffer = new BufferedInputStream(fileIn)) { byte[] bytes = new byte[(int) new File(path).length()]; buffer.read(bytes, 0, bytes.length); out.write(bytes, 0, bytes.length); } catch (IOException e) { e.printStackTrace(); } } }