Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

Есть приложение на java. Вот серверная часть: package serverUtils; import java.io.File;…

  1. User

    Есть приложение на java. Вот серверная часть: package serverUtils;

    import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.StandardCharsets;

    public class ConnectionManager { private static final String ACK_MESSAGE_PREFIX = “<%s>Ack”; private static final int BUFFER_SIZE = 1024 * 1024;

    ServerSocketChannel serverSocketChannel; int port;

    public ConnectionManager(int port) { this.port = port; }

    public void initialize() throws IOException { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(port)); serverSocketChannel.configureBlocking(false); System.out.println(“Server started on port " + port); System.out.println(”============ * ============"); }

    public void registerSelector(Selector selector) throws ClosedChannelException { serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); }

    public void processQuery(Selector selector, SelectionKey key) throws IOException { if (!key.isValid()) { return; } if (key.isAcceptable()) { acceptConnection(key, selector); } else if (key.isReadable()) { handleRead(key); } } private void acceptConnection(SelectionKey key, Selector selector) throws IOException { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel clientSocketChannel = serverSocketChannel.accept(); clientSocketChannel.configureBlocking(false); clientSocketChannel.register(selector, SelectionKey.OP_READ);

    System.out.println(“Accepted connection from " + clientSocketChannel.getRemoteAddress()); }

    private void handleRead(SelectionKey key) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); SocketChannel clientSocketChannel = (SocketChannel) key.channel(); int bytesRead; while ((bytesRead = clientSocketChannel.read(buffer)) > 0) { buffer.flip();

    // проверяем наличие данных в буфере if (buffer.remaining() < 8) { continue; }

    // читаем длину имени файла в байтах int nameLength = buffer.getInt();

    // проверяем наличие данных в буфере if (buffer.remaining() < nameLength + 4) { buffer.position(buffer.position() - 4); buffer.compact(); continue; }

    // читаем имя файла byte[] nameBytes = new byte[nameLength]; buffer.get(nameBytes); String fileName = new String(nameBytes, StandardCharsets.UTF_8);

    // читаем длину файла в байтах int fileLength = buffer.getInt();

    // проверяем наличие данных в буфере if (buffer.remaining() < fileLength + 8) { buffer.position(buffer.position() - 8); buffer.compact(); continue; }

    // читаем содержимое файла byte[] fileContent = new byte[fileLength]; buffer.get(fileContent, 0, fileLength);

    // проверяем разделитель long separator = buffer.getLong(); if (separator != 0) { throw new RuntimeException(“Invalid separator”); }

    // очищаем буфер buffer.clear();

    // сохраняем файл saveFile(fileName, fileContent);

    // отправляем подтверждение о сохранении файла sendAck(clientSocketChannel, fileName); }

    if (bytesRead == -1) { System.out.println(“Closed connection with " + clientSocketChannel.getRemoteAddress()); clientSocketChannel.close(); key.cancel(); System.out.println(”============ * ============”); } }

    private void saveFile(String filename, byte[] fileContent) throws IOException { File file = new File(“files\” + filename);

    System.out.println("Saving file " + filename);

    try (FileOutputStream outputStream = new FileOutputStream(file)) { outputStream.write(fileContent); } System.out.println(“File " + filename + " saved successfully”); }

    private void sendAck(SocketChannel clientSocketChannel, String filename) throws IOException { String ackMessage = String.format(ACK_MESSAGE_PREFIX, filename); byte[] ackMessageBytes = ackMessage.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(ackMessageBytes.length + Integer.BYTES); buffer.putInt(ackMessageBytes.length); buffer.put(ackMessageBytes); buffer.flip();

    while (buffer.hasRemaining()) { clientSocketChannel.write(buffer); }

    System.out.println("Sent acknowledgement for " + filename); buffer.clear(); // Очищаем буфер перед чтением новых данных } }

    package serverUtils;

    import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator;

    public class Console {

    public void start() throws IOException { ConnectionManager connectionManager = new ConnectionManager(6789);

    connectionManager.initialize();

    Selector selector = Selector.open(); connectionManager.registerSelector(selector);

    while (true) { int readyChannelsCount = selector.select(); if (readyChannelsCount == 0) { continue; } Iterator selectedKeysIterator = selector.selectedKeys().iterator(); while (selectedKeysIterator.hasNext()) { SelectionKey key = selectedKeysIterator.next(); selectedKeysIterator.remove(); connectionManager.processQuery(selector, key); } } } }

    Ее нужно исправить, добавив возможность обработки нескольких клиентов. Например, если один из клиентов остановился на передаче файла где-то на половине, и чтобы не крутиться в холостом цикле, в это время необходимо обрабатывать запросы других клиентов. Для достижения данного условия необходимо создать контекст соединения и связать его с конкретным соединением (Selection Key) и получать его через метод attachment. В этом же контексте можно хранить название файла, текущий состояние буффера, этап передачи файла.

  2. Assistant

    Для обработки нескольких клиентов необходимо внести изменения в ваш код. Первым делом, нужно создать новый класс ConnectionContext, который будет хранить информацию о состоянии клиента, такую как название файла, текущее состояние буфера и этап передачи файла.

    class ConnectionContext {
        private String fileName;
        private ByteBuffer buffer;
        private ConnectionState state;
    
        public ConnectionContext() {
            buffer = ByteBuffer.allocate(ConnectionManager.BUFFER_SIZE);
            state = ConnectionState.FILE_NAME_LENGTH;
        }
    
        public enum ConnectionState {
            FILE_NAME_LENGTH,
            FILE_NAME,
            FILE_LENGTH,
            FILE_CONTENT,
            SEPARATOR,
            ACK
        }
    
        // добавить геттеры и сеттеры для полей
    }
    

    Также следует выполнить ряд изменений в коде класса ConnectionManager. В методе acceptConnection нужно создать новый экземпляр класса ConnectionContext и привязать его к текущему ключу выборки.

    private void acceptConnection(SelectionKey key, Selector selector) throws IOException {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        SocketChannel clientSocketChannel = serverSocketChannel.accept();
        clientSocketChannel.configureBlocking(false);
    
        ConnectionContext context = new ConnectionContext();
        SelectionKey clientKey = clientSocketChannel.register(selector, SelectionKey.OP_READ);
        clientKey.attach(context);
    
        System.out.println("Accepted connection from " + clientSocketChannel.getRemoteAddress());
    }
    

    В методе handleRead следует изменить обработку запросов так, чтобы она пользовалась экземпляром класса ConnectionContext. Теперь, код будет восстанавливаться с последнего сохраненного состояния, и не будет останавливаться ни на какой из стадий передачи файла.

    private void handleRead(SelectionKey key) throws IOException {
        SocketChannel clientSocketChannel = (SocketChannel) key.channel();
        ConnectionContext context = (ConnectionContext) key.attachment();
        ByteBuffer buffer = context.getBuffer();
    
        int bytesRead;
        while ((bytesRead = clientSocketChannel.read(buffer)) > 0) {
    
            buffer.flip();
    
            while (buffer.hasRemaining()) {
                switch (context.getState()) {
    
                    case FILE_NAME_LENGTH:
                        if (buffer.remaining() < Integer.BYTES) {
                            buffer.compact();
                            return;
                        }
                        int nameLength = buffer.getInt();
                        context.setFileNameLength(nameLength);
                        context.setState(ConnectionState.FILE_NAME);
    
                    case FILE_NAME:
                        if (buffer.remaining() < context.getFileNameLength()) {
                            buffer.compact();
                            return;
                        }
                        byte[] nameBytes = new byte[context.getFileNameLength()];
                        buffer.get(nameBytes);
                        String fileName = new String(nameBytes, StandardCharsets.UTF_8);
                        context.setFileName(fileName);
                        context.setState(ConnectionState.FILE_LENGTH);
    
                    case FILE_LENGTH:
                        if (buffer.remaining() < Integer.BYTES) {
                            buffer.compact();
                            return;
                        }
                        int fileLength = buffer.getInt();
                        context.setFileLength(fileLength);
                        context.setState(ConnectionState.FILE_CONTENT);
    
                    case FILE_CONTENT:
                        if (buffer.remaining() < context.getFileLength()) {
                            buffer.compact();
                            return;
                        }
                        byte[] fileContent = new byte[context.getFileLength()];
                        buffer.get(fileContent, 0, context.getFileLength());
                        saveFile(context.getFileName(), fileContent);
                        context.setState(ConnectionState.SEPARATOR);
    
                    case SEPARATOR:
                        if (buffer.remaining() < Long.BYTES) {
                            buffer.compact();
                            return;
                        }
                        long separator = buffer.getLong();
                        if (separator != 0) {
                            throw new RuntimeException("Invalid separator");
                        }
                        sendAck(clientSocketChannel, context.getFileName());
                        context.setState(ConnectionState.ACK);
    
                    case ACK:
                        break;
                }
            }
    
            buffer.clear();
        }
    
        if (bytesRead == -1) {
            System.out.println("Closed connection with " + clientSocketChannel.getRemoteAddress());
            clientSocketChannel.close();
            key.cancel();
            System.out.println("============ * ============");
        }
    }
    

    С использованием ConnectionContext ваш сервер теперь сможет обрабатывать несколько клиентов одновременно, и, если передача файла замедлена или остановлена, сервер будет продолжать обрабатывать запросы других клиентов.

  3. User

    Исправь хранить в памяти файл, так как он может не влезть полностью в оперативку, нужно считывать батчами и загружать в файл. package serverUtils;

    import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.StandardCharsets;

    public class ConnectionManager { private static final String ACK_MESSAGE_PREFIX = "<%s>Ack"; static final int BUFFER_SIZE = 1024 * 1024;

    ServerSocketChannel serverSocketChannel;
    int port;
    
    public ConnectionManager(int port) {
        this.port = port;
    }
    
    public void initialize() throws IOException {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        serverSocketChannel.configureBlocking(false);
        System.out.println("Server started on port " + port);
        System.out.println("============ * ============");
    }
    
    public void registerSelector(Selector selector) throws ClosedChannelException {
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }
    
    public void processQuery(Selector selector, SelectionKey key) throws IOException {
        if (!key.isValid()) {
            return;
        }
        if (key.isAcceptable()) {
            acceptConnection(key, selector);
        } else if (key.isReadable()) {
            handleRead(key);
        }
    }
    private void acceptConnection(SelectionKey key, Selector selector) throws IOException {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        SocketChannel clientSocketChannel = serverSocketChannel.accept();
        clientSocketChannel.configureBlocking(false);
        // Attach new ConnectionContext instance to the selection key
        ConnectionContext context = new ConnectionContext();
        clientSocketChannel.register(selector, SelectionKey.OP_READ, context);
    
        System.out.println("Accepted connection from " + clientSocketChannel.getRemoteAddress());
    }
    
    private void handleRead(SelectionKey key) throws IOException {
        SocketChannel clientSocketChannel = (SocketChannel) key.channel();
        ConnectionContext connectionContext = (ConnectionContext) key.attachment();
    

    // if (connectionContext == null) { // connectionContext = new ConnectionContext(); // key.attach(connectionContext); // }

        ByteBuffer buffer = connectionContext.buffer;
        int bytesRead = clientSocketChannel.read(buffer);
    
        if (bytesRead < 0) {
            System.out.println("Closed connection with " + clientSocketChannel.getRemoteAddress());
            clientSocketChannel.close();
            key.cancel();
            System.out.println("============ * ============");
            return;
        }
    
        buffer.flip();
    
        // handle file transmission
        if (connectionContext.fileStarted) {
            // check if we need more data to continue reading the file
            if (connectionContext.fileName != null && connectionContext.fileLength >= 0 &&
                    buffer.remaining() >= connectionContext.fileLength + Long.BYTES) {
    
                // read the file contents
                byte[] fileContent = new byte[connectionContext.fileLength];
                buffer.get(fileContent);
    
                // check the separator
                connectionContext.separator = buffer.getLong();
                if (connectionContext.separator != 0) {
                    throw new RuntimeException("Invalid separator");
                }
    
                // save the file and send an acknowledgement
                saveFile(connectionContext.fileName, fileContent);
                sendAck(clientSocketChannel, connectionContext.fileName);
    
                // reset context for next file transfer
                connectionContext.fileStarted = false;
                connectionContext.fileCompleted = true;
                connectionContext.fileName = null;
                connectionContext.fileLength = -1;
    
                // handle any remaining data in buffer
                if (buffer.remaining() > 0) {
                    handleRead(key);
                    return;
                }
            }
        } else {
            // read the header of the file transfer
            while (buffer.hasRemaining() && !connectionContext.fileStarted) {
                // read the name length
                if (connectionContext.fileName == null && buffer.remaining() >= Integer.BYTES) {
                    int nameLength = buffer.getInt();
                    byte[] nameBytes = new byte[nameLength];
                    buffer.get(nameBytes);
                    connectionContext.fileName = new String(nameBytes, StandardCharsets.UTF_8);
                }
    
                // read the file length
                if (connectionContext.fileLength < 0 && buffer.remaining() >= Integer.BYTES) {
                    connectionContext.fileLength = buffer.getInt();
                    if (connectionContext.fileLength < 0) {
                        throw new RuntimeException("Invalid file length");
                    }
                    connectionContext.fileStarted = true;
    
                    // check if we need more data to continue reading the file
                    if (buffer.remaining() < connectionContext.fileLength + Long.BYTES) {
                        buffer.compact();
                        return;
                    }
                }
            }
        }
    
        // handle file transmission continued with remaining data in buffer
        if (connectionContext.fileStarted && !connectionContext.fileCompleted &&
                buffer.remaining() >= connectionContext.fileLength + Long.BYTES) {
    
            // read the file contents
            byte[] fileContent = new byte[connectionContext.fileLength];
            buffer.get(fileContent);
    
            // check the separator
            connectionContext.separator = buffer.getLong();
            if (connectionContext.separator != 0) {
                throw new RuntimeException("Invalid separator");
            }
    
            // save the file and send an acknowledgement
            saveFile(connectionContext.fileName, fileContent);
            sendAck(clientSocketChannel, connectionContext.fileName);
    
            // reset context for next file transfer
            connectionContext.fileStarted = false;
            connectionContext.fileCompleted = true;
            connectionContext.fileName = null;
            connectionContext.fileLength = -1;
    
            // handle any remaining data in buffer
            if (buffer.remaining() > 0) {
                handleRead(key);
                return;
            }
        }
    
        buffer.compact();
    }
    
    
    
    
    
    private void saveFile(String filename, byte[] fileContent) throws IOException {
        File file = new File("files\\" + filename);
    
        System.out.println("Saving file " + filename);
    
        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            outputStream.write(fileContent);
        }
        System.out.println("File " + filename + " saved successfully");
    }
    
    private void sendAck(SocketChannel clientSocketChannel, String filename) throws IOException {
        String ackMessage = String.format(ACK_MESSAGE_PREFIX, filename);
        byte[] ackMessageBytes = ackMessage.getBytes();
        ByteBuffer buffer = ByteBuffer.allocate(ackMessageBytes.length + Integer.BYTES);
        buffer.putInt(ackMessageBytes.length);
        buffer.put(ackMessageBytes);
        buffer.flip();
    
        while (buffer.hasRemaining()) {
            clientSocketChannel.write(buffer);
        }
    
        System.out.println("Sent acknowledgement for " + filename);
        buffer.clear(); // Очищаем буфер перед чтением новых данных
    }
    

    }

  4. Assistant

    Чтобы сохранять содержимое файла по частям, нужно изменить ConnectionContext и добавить новое состояние FILE_BATCH_CONTENT. Затем в методе handleRead обработать запись файла по частям:

    class ConnectionContext {
        private String fileName;
        private ByteBuffer buffer;
        private ConnectionState state;
        private int fileNameLength;
        private int fileLength;
        private int remainingFileBytes;
        private FileOutputStream fileOutputStream;
    
        public ConnectionContext() {
            buffer = ByteBuffer.allocate(ConnectionManager.BUFFER_SIZE);
            state = ConnectionState.FILE_NAME_LENGTH;
        }
    
        // ... оставшийся код ConnectionContext
    
        public enum ConnectionState {
            FILE_NAME_LENGTH,
            FILE_NAME,
            FILE_LENGTH,
            FILE_CONTENT,
            FILE_BATCH_CONTENT, // добавить новое состояние
            SEPARATOR,
            ACK
        }
    
        // ... геттеры и сеттеры для всех полей
    }
    

    И в методе handleRead обрабатываем запись файла по частям:

    private void handleRead(SelectionKey key) throws IOException {
        SocketChannel clientSocketChannel = (SocketChannel) key.channel();
        ConnectionContext context = (ConnectionContext) key.attachment();
        ByteBuffer buffer = context.getBuffer();
    
        int bytesRead = clientSocketChannel.read(buffer);
        if (bytesRead < 0) {
            System.out.println("Closed connection with " + clientSocketChannel.getRemoteAddress());
            clientSocketChannel.close();
            key.cancel();
            System.out.println("============ * ============");
            return;
        }
    
        buffer.flip();
    
        while (buffer.hasRemaining()) {
            switch (context.getState()) {
                // ... предыдущие состояния
    
                case FILE_CONTENT:
                    File file = new File("files\\" + context.getFileName());
                    context.setFileOutputStream(new FileOutputStream(file));
                    context.setState(ConnectionState.FILE_BATCH_CONTENT);
                    context.setRemainingFileBytes(context.getFileLength());
                    // не использовать здесь 'break' - перейдем к следующему состоянию
    
                case FILE_BATCH_CONTENT:
                    int batchSize = Math.min(buffer.remaining(), context.getRemainingFileBytes());
                    if (batchSize > 0) {
                        byte[] batch = new byte[batchSize];
                        buffer.get(batch);
                        context.getFileOutputStream().write(batch);
                        context.setRemainingFileBytes(context.getRemainingFileBytes() - batchSize);
                    }
    
                    if (context.getRemainingFileBytes() == 0) {
                        context.getFileOutputStream().close();
                        context.setState(ConnectionState.SEPARATOR);
                    } else {
                        buffer.compact();
                        return;
                    }
                    break;
    
                // ... последующие состояния
    }
    }
    
  5. User

    НАладь работу этих блоков: package serverUtils;

    import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator;

    public class Console {

    public void start() throws IOException {
        ConnectionManager connectionManager = new ConnectionManager(6789);
    
        connectionManager.initialize();
    
        Selector selector = Selector.open();
        connectionManager.registerSelector(selector);
    
        while (true) {
            int readyChannelsCount = selector.selectNow();
            if (readyChannelsCount == 0) {
                continue;
            }
            Iterator<SelectionKey> selectedKeysIterator = selector.selectedKeys().iterator();
            while (selectedKeysIterator.hasNext()) {
                SelectionKey key = selectedKeysIterator.next();
                selectedKeysIterator.remove();
                connectionManager.processQuery(selector, key);
            }
        }
    }
    

    }

    package serverUtils;

    import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.StandardCharsets;

    public class ConnectionManager { private static final String ACK_MESSAGE_PREFIX = "<%s>Ack"; static final int BUFFER_SIZE = 1024 * 1024;

    ServerSocketChannel serverSocketChannel;
    int port;
    
    public ConnectionManager(int port) {
        this.port = port;
    }
    
    public void initialize() throws IOException {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        serverSocketChannel.configureBlocking(false);
        System.out.println("Server started on port " + port);
        System.out.println("============ * ============");
    }
    
    public void registerSelector(Selector selector) throws ClosedChannelException {
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }
    
    public void processQuery(Selector selector, SelectionKey key) throws IOException {
        if (!key.isValid()) {
            return;
        }
        if (key.isAcceptable()) {
            acceptConnection(key, selector);
        } else if (key.isReadable()) {
            handleRead(key);
        }
    }
    private void acceptConnection(SelectionKey key, Selector selector) throws IOException {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        SocketChannel clientSocketChannel = serverSocketChannel.accept();
        clientSocketChannel.configureBlocking(false);
        // Attach new ConnectionContext instance to the selection key
        ConnectionContext context = new ConnectionContext();
        clientSocketChannel.register(selector, SelectionKey.OP_READ, context);
    
        System.out.println("Accepted connection from " + clientSocketChannel.getRemoteAddress());
    }
    
    private void handleRead(SelectionKey key) throws IOException {
        SocketChannel clientSocketChannel = (SocketChannel) key.channel();
        ConnectionContext connectionContext = (ConnectionContext) key.attachment();
    
        System.out.println(connectionContext);
    
        if (connectionContext == null) {
            connectionContext = new ConnectionContext();
            key.attach(connectionContext);
        }
    
        ByteBuffer buffer = connectionContext.buffer;
        int bytesRead = clientSocketChannel.read(buffer);
    
        if (bytesRead < 0) {
            System.out.println("Closed connection with " + clientSocketChannel.getRemoteAddress());
            clientSocketChannel.close();
            key.cancel();
            System.out.println("============ * ============");
            return;
        }
    
        buffer.flip();
    
        // handle file transmission
        if (connectionContext.fileStarted) {
            // check if we need more data to continue reading the file
            if (connectionContext.fileName != null && connectionContext.fileLength >= 0 &&
                    buffer.remaining() >= connectionContext.fileLength + Long.BYTES) {
    
                // read the file contents
                byte[] fileContent = new byte[connectionContext.fileLength];
                buffer.get(fileContent);
    
                // check the separator
                connectionContext.separator = buffer.getLong();
                if (connectionContext.separator != 0L) {
                    throw new RuntimeException("Invalid separator");
                }
    
                // save the file and send an acknowledgement
                saveFile(connectionContext.fileName, fileContent);
                sendAck(clientSocketChannel, connectionContext.fileName);
    
                // reset context for next file transfer
                connectionContext.fileStarted = false;
                connectionContext.fileCompleted = true;
                connectionContext.fileName = null;
                connectionContext.fileLength = -1;
    
                // handle any remaining data in buffer
                if (buffer.remaining() > 0) {
                    handleRead(key);
                    return;
                }
            }
        } else {
            // read the header of the file transfer
            while (buffer.hasRemaining() && !connectionContext.fileStarted) {
                // read the name length
                if (connectionContext.fileName == null && buffer.remaining() >= Integer.BYTES) {
                    int nameLength = buffer.getInt();
                    byte[] nameBytes = new byte[nameLength];
                    buffer.get(nameBytes);
                    connectionContext.fileName = new String(nameBytes, StandardCharsets.UTF_8);
                }
    
                // read the file length
                if (connectionContext.fileLength < 0 && buffer.remaining() >= Integer.BYTES) {
                    connectionContext.fileLength = buffer.getInt();
                    if (connectionContext.fileLength < 0) {
                        throw new RuntimeException("Invalid file length");
                    }
                    connectionContext.fileStarted = true;
    
                    // check if we need more data to continue reading the file
                    if (buffer.remaining() < BUFFER_SIZE) {
                        buffer.compact();
                        return;
                    }
                }
            }
        }
    
        // handle file transmission continued with remaining data in buffer
        if (connectionContext.fileStarted && !connectionContext.fileCompleted &&
                buffer.remaining() >= connectionContext.fileLength + Long.BYTES) {
    
            // read the file contents
            byte[] fileContent = new byte[connectionContext.fileLength];
            buffer.get(fileContent);
    
            // check the separator
            connectionContext.separator = buffer.getLong();
            if (connectionContext.separator != 0L) {
                throw new RuntimeException("Invalid separator");
            }
    
            // save the file and send an acknowledgement
            saveFile(connectionContext.fileName, fileContent);
            sendAck(clientSocketChannel, connectionContext.fileName);
    
            // reset context for next file transfer
            connectionContext.fileStarted = false;
            connectionContext.fileCompleted = true;
            connectionContext.fileName = null;
            connectionContext.fileLength = -1;
    
            // handle any remaining data in buffer
            if (buffer.remaining() > 0) {
                handleRead(key);
                return;
            }
        }
    
        buffer.compact();
    }
    
    private void saveFile(String filename, byte[] fileContent) throws IOException {
        File file = new File("files\\" + filename);
    
        System.out.println("Saving file " + filename);
    
        try (FileOutputStream outputStream = new FileOutputStream(file, true)) {
            int offset = 0;
            while (offset < fileContent.length) {
                int bytesToWrite = Math.min(BUFFER_SIZE, fileContent.length - offset);
                outputStream.write(fileContent, offset, bytesToWrite);
                offset += bytesToWrite;
            }
            outputStream.flush();
        }
        System.out.println("File " + filename + " saved successfully");
    }
    
    
    private void sendAck(SocketChannel clientSocketChannel, String filename) throws IOException {
        String ackMessage = String.format(ACK_MESSAGE_PREFIX, filename);
        byte[] ackMessageBytes = ackMessage.getBytes();
        ByteBuffer buffer = ByteBuffer.allocate(ackMessageBytes.length + Integer.BYTES);
        buffer.putInt(ackMessageBytes.length);
        buffer.put(ackMessageBytes);
        buffer.flip();
    
        while (buffer.hasRemaining()) {
            clientSocketChannel.write(buffer);
        }
    
        System.out.println("Sent acknowledgement for " + filename);
        buffer.clear(); // Очищаем буфер перед чтением новых данных
    }
    

    }

    package serverUtils;

    import java.nio.ByteBuffer;

    public class ConnectionContext { public String fileName; public ByteBuffer buffer; public int fileLength = -1; public long separator = 0L; public boolean fileStarted = false; public boolean fileCompleted = false;

    public ConnectionContext() {
        this.buffer = ByteBuffer.allocate(ConnectionManager.BUFFER_SIZE);
    }
    

    }

    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 {
    

    // connect(); sendFile(file, fis); receiveConfirmation(); // closeConnection(); } 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) {
            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);
    }
    

    }

  6. Assistant

    Для того чтобы исправить блоки кода из вашего комментария следует сделать следующие изменения:

    1. В package clientUtils.ConnectionManager в методе sendFile удалите закрытие fileInputStream fis.close(); и передайте его закрытие вызывающему коду. Для этого, следует закрыть fis в makeRequest методе после вызова receiveConfirmation():
    void makeRequest(File file, FileInputStream fis) throws IOException {
        sendFile(file, fis);
        receiveConfirmation();
        fis.close(); // Закрыть FileInputStream здесь
    }
    
    1. В package serverUtils.ConnectionManager в методе saveFile измените ожидание объема буфера на ожидание объема файла в строке с условной проверкой:
    if (buffer.remaining() < context.fileLength + Long.BYTES) {
        buffer.compact();
        return;
    }
    

    Эти изменения должны корректно исправить проблему с работой блоков кода.

  7. User

    При работе с двумя клиентами появляется ошибка Exception in thread "main" java.nio.BufferUnderflowException at java.base/java.nio.HeapByteBuffer.get(HeapByteBuffer.java:183) at java.base/java.nio.ByteBuffer.get(ByteBuffer.java:826) at serverUtils.ConnectionManager.handleRead(ConnectionManager.java:118) at serverUtils.ConnectionManager.processQuery(ConnectionManager.java:41) at serverUtils.Console.start(Console.java:27) at Server.main(Server.java:10)

  8. Assistant

    Давайте разберемся с проблемой BufferUnderflowException. Эта ошибка возникает, когда буфер не имеет достаточного количества данных для корректной работы с ним. Я думаю, что проблема возникает из-за того, что мы сразу переходим к следующему блоку при достаточном количестве данных. Воспользуемся break вместо прямого возврата функции для продолжения работы с данными.

    Давайте внесем изменение в метод handleRead класса ConnectionManager:

    1. Замените следующие строки кода:

      if (buffer.remaining() < context.fileLength + Long.BYTES) {
          buffer.compact();
          return;
      }
      

      на:

      if (buffer.remaining() < context.fileLength + Long.BYTES) {
          buffer.compact();
          break;
      }
      

    Теперь сервер должен корректно обрабатывать два клиента одновременно без возникновения ошибки BufferUnderflowException.

  9. User

    При работе с двумя клиентами появляется ошибка Exception in thread “main” java.nio.BufferUnderflowException at java.base/java.nio.HeapByteBuffer.get(HeapByteBuffer.java:183) at java.base/java.nio.ByteBuffer.get(ByteBuffer.java:826) at serverUtils.ConnectionManager.handleRead(ConnectionManager.java:118) at serverUtils.ConnectionManager.processQuery(ConnectionManager.java:41) at serverUtils.Console.start(Console.java:27) at Server.main(Server.java:10)

  10. Assistant

    Извините за предыдущий ответ. Давайте рассмотрим другой подход к решению данной проблемы.

    При использовании неблокирующего режима, selectNow() может вызывать повторение передачи данных, что может привести к ошибке BufferUnderflowException. Вместо selectNow() нужно использовать select(), который будет блокировать поток до готовности канала.

    1. В методе start класса Console, замените:
    int readyChannelsCount = selector.selectNow();
    

    на:

    int readyChannelsCount = selector.select();
    

    Это изменение должно корректно исправить проблему с работой двух клиентов одновременно без возникновения ошибки BufferUnderflowException.

  11. User

    Так клиенты вообще не получают ответ

  12. Assistant

    Извините за путаницу. Вернемся к исходной проблеме и попробуем решить ее другим способом. Для этого измените файл ConnectionManager.java.

    1. В методе handleRead замените return на break там, где стоит проверка buffer.remaining() < context.fileLength + Long.BYTES. Таким образом обработка выборки будет продолжаться, если есть доступные каналы:
    if (buffer.remaining() < context.fileLength + Long.BYTES) {
        buffer.compact();
        break;
    }
    
    1. Верните selector.select() вместо selector.selectNow() в методе start класса Console. В моем предыдущем ответе я указал изменить это, но это было лишним и могло вызвать блокировку потока:
    int readyChannelsCount = selector.select();
    

    С этими изменениями клиенты должны получать ответы от сервера, и сервер сможет обрабатывать нескольких клиентов одновременно без ошибки BufferUnderflowException.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.