Код клиента передает большие файлы с помощью кода package clientUtils; import java.io.*;…
- User
Код клиента передает большие файлы с помощью кода package clientUtils;
import java.io.*; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets;
public class ConnectionManager { String ip; int port; SocketChannel socketChannel;
public ConnectionManager(String ip, int port) { this.ip = ip; this.port = port; } void makeRequest(File file) throws IOException { sendFile(file); receiveConfirmation(); } void connect() throws IOException { System.out.println("Connected to the server"); socketChannel = SocketChannel.open(new InetSocketAddress(ip, port)); socketChannel.configureBlocking(true); } void closeConnection() throws IOException { socketChannel.close(); System.out.println("Connection closed"); } private void sendFile(File file) throws IOException { // Создаем байтовый массив для передачи имени файла и его длины byte[] nameBytes = file.getName().getBytes(StandardCharsets.UTF_8); ByteBuffer nameLengthBuffer = ByteBuffer.allocate(Integer.BYTES).putInt(nameBytes.length); nameLengthBuffer.flip(); // Отправляем длину имени файла и само имя socketChannel.write(nameLengthBuffer); ByteBuffer nameBuffer = ByteBuffer.wrap(nameBytes); socketChannel.write(nameBuffer); // Отправляем длину файла long fileLength = file.length(); ByteBuffer fileLengthBuffer = ByteBuffer.allocate(Long.BYTES).putLong(fileLength); fileLengthBuffer.flip(); socketChannel.write(fileLengthBuffer); // Получаем канал для чтения файла FileChannel fileChannel = new FileInputStream(file).getChannel(); int chunkSize = 1024 * 1024; // 1 МБ // Читаем данные из файла по блокам и отправляем их ByteBuffer buffer = ByteBuffer.allocate(chunkSize); long bytesSent = 0; while (bytesSent < fileLength) { int bytesRead = fileChannel.read(buffer); if (bytesRead == -1) { // конец файла break; } buffer.flip(); while (buffer.hasRemaining()) { socketChannel.write(buffer); // отправляем текущий блок } bytesSent += bytesRead; // увеличиваем количество переданных байт System.out.println(bytesSent + " of " + fileLength); buffer.clear(); // очищаем буфер для следующего чтения } socketChannel.write(ByteBuffer.allocate(Long.BYTES)); // разделитель fileChannel.close(); System.out.println("File " + file.getName() + " sent successfully"); } private void receiveConfirmation() throws IOException { // Читаем длину сообщения ByteBuffer lengthBuffer = ByteBuffer.allocate(Integer.BYTES); socketChannel.read(lengthBuffer); lengthBuffer.flip(); int messageLength = lengthBuffer.getInt(); // Читаем само сообщение ByteBuffer messageBuffer = ByteBuffer.allocate(messageLength); int bytesRead = 0; while (bytesRead < messageLength) { bytesRead += socketChannel.read(messageBuffer); } messageBuffer.rewind(); byte[] messageBytes = new byte[messageBuffer.remaining()]; messageBuffer.get(messageBytes); String message = new String(messageBytes, StandardCharsets.UTF_8); System.out.println("Received file: " + message); } - Assistant