Есть код клиента и сервера на java. нужно улучшить код так, чтобы можно было передавать…
- User
Есть код клиента и сервера на java. нужно улучшить код так, чтобы можно было передавать большие файлы, без изменения буфера package clientUtils;
import java.io.*; import java.net.InetSocketAddress; import java.nio.ByteBuffer; 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, FileInputStream fis) throws IOException { sendFile(file, fis); 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, FileInputStream fis) 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); // Отправляем длину файла int fileLength = (int) file.length(); ByteBuffer fileLengthBuffer = ByteBuffer.allocate(Integer.BYTES).putInt(fileLength); fileLengthBuffer.flip(); socketChannel.write(fileLengthBuffer); // Определяем размер куска int chunkSize = 1024; byte[] buffer = new byte[chunkSize]; // Читаем данные из файла по кускам и отправляем их int totalBytesRead = 0; while (totalBytesRead < fileLength) { System.out.println(totalBytesRead + " of " + fileLength); int bytesRead = fis.read(buffer, 0, Math.min(chunkSize, fileLength - totalBytesRead)); if (bytesRead > 0) { // если прочитали что-то из файла ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead); socketChannel.write(byteBuffer); // отправляем текущий кусок totalBytesRead += bytesRead; // увеличиваем количество переданных байт } } socketChannel.write(ByteBuffer.allocate(Long.BYTES)); // разделитель fis.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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.