Вмешательство InputStream при двусторонней передаче файла через сокеты - PullRequest
0 голосов
/ 12 апреля 2020

После редактирования моего кода со всеми вашими предложениями, а также сжатия кода, где я могу точно указать строку кода, которая вызывает проблему. Код сервера: `

publi c класс Server2 {

public static void main(String args[]) throws Exception {

    ServerSocket servsock = null;
    Socket sock = null;
    int SOCKET_PORT = 12362;

    InputStream is = null;
    FileInputStream fis = null;
    BufferedInputStream bis = null;

    OutputStream os = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;

    String FILE_TO_SEND = "SFileToBeSent.txt";
    String FILE_TO_RECEIVED = "CFileReceived.txt";
    int FILE_SIZE = 6022386;

    try {

        System.out.println("Server created.");
        servsock = new ServerSocket(SOCKET_PORT); // creates servsock with socket port
        while (true) {

            System.out.println("Waiting for connection...");
            try {

                sock = servsock.accept(); // accepts a socket connection
                System.out.println("Accepted connection : " + sock);
                System.out.println();

                os = sock.getOutputStream(); // sets Output Stream using the sockets output stream
                is = sock.getInputStream(); // get input stream from socket

                // ----------------------------------------------------------------------------------------------------
                // ----------------------------------------------------------------------------------------------------

                // send file
                File myFile = new File(FILE_TO_SEND); // creates a file using file to send path
                byte[] bytearraySent = new byte[(int) myFile.length()]; // creates a byte array the size of myFile

                try {

                    // reads the contents of FILE_TO_SEND into a BufferedInputStream
                    fis = new FileInputStream(myFile); // creates new FIS from myFile
                    bis = new BufferedInputStream(fis); // creates BIS with the FIS
                    bis.read(bytearraySent, 0, bytearraySent.length); // copies the BIS byte array into the byte array

                    // prints to console filename and size
                    System.out.println("Sending " + FILE_TO_SEND + "(" + bytearraySent.length + " bytes)");
                    System.out.println("byte array from file to send:" + bytearraySent);

                    // copies the byte array into the output stream therefore sending it through the
                    // socket
                    os.write(bytearraySent, 0, bytearraySent.length);
                    os.flush(); // flush/clears the output stream
                } finally {

                    fis.close();
                    bis.close();
                }

                System.out.println();
                System.out.println("sendFile complete");
                System.out.println();

                // ----------------------------------------------------------------------------------------------------
                // ----------------------------------------------------------------------------------------------------

                // receive file
                int bytesRead;

                byte[] bytearrayReceived = new byte[FILE_SIZE]; // creates byte aray using file size
                fos = new FileOutputStream(FILE_TO_RECEIVED); // creates file from path
                bos = new BufferedOutputStream(fos); // creates BOS from FOS
                int current = 0; // equals the two integers for comparisons later
                try {

                    System.out.println(String.format("Bytes available from received file:  %d", is.available()));

                    System.out.println("byte array from file to receive:  " + bytearrayReceived); // debug purposes

                    while ((bytesRead = is.read(bytearrayReceived)) != -1) {

                        System.out.println("amount of bytes that was read for while:  " + bytesRead);

                        bos.write(bytearrayReceived, 0, bytesRead);
                        System.out.println("bos.write");

                        current += bytesRead;
                        System.out.println("current += bytesRead;");
                    }
                    System.out.println("File " + FILE_TO_RECEIVED + " downloaded (" + current + " bytes read)");
                } finally {

                    fos.close();
                    bos.close();
                }

                System.out.println();
                System.out.println("receiveFile complete");
                System.out.println();

                // ----------------------------------------------------------------------------------------------------
                // ----------------------------------------------------------------------------------------------------

            } // end of try
            finally {

                // if any streams or sockets are not null, the close them
                if (os != null)
                    os.close();
                if (is != null)
                    is.close();
                if (sock != null)
                    sock.close();
            } // end of finally
        } // end of while
    } // end of try
    finally {

        if (servsock != null)
            servsock.close();
    } // end of finally
}

}

publi c class Client2 {

public static void main(String args[]) throws Exception {

    Socket sock = null; // used in main
    String SERVER = "localhost"; // local host
    int SOCKET_PORT = 12362; // you may change this

    InputStream is = null;
    FileInputStream fis = null;
    BufferedInputStream bis = null;

    OutputStream os = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;

    String FILE_TO_RECEIVED = "SFileReceived.txt";
    String FILE_TO_SEND = "CFileToBeSent.txt";
    int FILE_SIZE = 6022386;

    try {

        sock = new Socket(SERVER, SOCKET_PORT);
        System.out.println("Connecting...");
        System.out.println();

        // get input and output from socket
        is = sock.getInputStream(); // get input stream from socket
        os = sock.getOutputStream(); // get output stream from socket

        // ----------------------------------------------------------------------------------------------------
        // ----------------------------------------------------------------------------------------------------

        // receive file
        int bytesRead;

        byte[] bytearrayReceived = new byte[FILE_SIZE]; // creates byte aray using file size
        fos = new FileOutputStream(FILE_TO_RECEIVED); // creates file from path
        bos = new BufferedOutputStream(fos); // creates BOS from FOS
        int current = 0; // equals the two integers for comparisons later
        try {

            System.out.println(String.format("Bytes available from received file:  %d", is.available()));

            System.out.println("byte array from file to receive:  " + bytearrayReceived); // debug purposes

            while ((bytesRead = is.read(bytearrayReceived)) != -1) {
                System.out.println("amount of bytes that was read for while:  " + bytesRead);

                bos.write(bytearrayReceived, 0, bytesRead);
                System.out.println("bos.write");

                current += bytesRead;
                System.out.println("current += bytesRead;");

            }
            System.out.println("File " + FILE_TO_RECEIVED + " downloaded (" + current + " bytes read)");
        } finally {

            fos.close();
            bos.close();
        }

        System.out.println();
        System.out.println("receiveFile() complete");
        System.out.println();

        // ----------------------------------------------------------------------------------------------------
        // ----------------------------------------------------------------------------------------------------

        // send file
        File myFile = new File(FILE_TO_SEND); // creates a file using file to send path
        byte[] bytearraySent = new byte[(int) myFile.length()]; // creates a byte array the size of myFile

        try {

            // reads the contents of FILE_TO_SEND into a BufferedInputStream
            fis = new FileInputStream(myFile); // creates new FIS from myFile
            bis = new BufferedInputStream(fis); // creates BIS with the FIS
            bis.read(bytearraySent, 0, bytearraySent.length); // copies the BIS byte array into the byte array

            // prints to console filename and size
            System.out.println("Sending " + FILE_TO_SEND + "(" + bytearraySent.length + " bytes)");
            System.out.println("byte array from file to send:" + bytearraySent);

            // copies the byte array into the output stream therefore sending it through the
            // socket
            os.write(bytearraySent, 0, bytearraySent.length);
            os.flush(); // flush/clears the output stream
        } finally {

            fis.close();
            bis.close();
        }

        System.out.println();
        System.out.println("sendFile() complete");
        System.out.println();

        // ----------------------------------------------------------------------------------------------------
        // ----------------------------------------------------------------------------------------------------

    } // end of try
    finally {

        if (sock != null)
            sock.close();
        if (os != null)
            os.close();
        if (is != null)
            is.close();
    } // end of finally
}

}

Выход сервера: --------------------

Сервер создан.

Ожидание соединения ...

Допустимое соединение: сокет [addr = / 127.0.0.1, порт = 51565, localport = 12362]

Отправка SFileToBeSent.txt (32 байта)

байтовый массив из файла отправить: [B@4e25154f

sendFile complete

Доступно байт из полученного файла: 0

байтовый массив из файла для получения: [B@70dea4e

Вывод клиента --------------------

Подключение ...

Доступно байт из полученного файла: 32

байтовый массив из файла для получения: [B@4e25154f

количество байтов, которые были прочитаны за время: 32

bos.write

current + = bytesRead


У меня все еще есть проблема с InputStream, и я обнаружил при отладке, что и сервер, и клиент застряли на w оператор hile (), который находится в разделе приема. Для сервера он останавливается немедленно, тогда как клиент проходит через while l oop один раз, а затем останавливается при обращении к оператору while.

Если у кого-либо есть какие-либо предложения или решения, то это будет высоко оценено!

1 Ответ

0 голосов
/ 12 апреля 2020

Во-первых, ваш метод receiveFile должен читать ввод и записывать вывод в al oop. Во-вторых, закройте файлы после завершения, иначе у вас может возникнуть утечка ресурсов.

publi c stati c void receiveFile () выдает IOException {

byte[] mybytearray = new byte[FILE_SIZE]; // creates byte aray using file size
fos = new FileOutputStream(FILE_TO_RECEIVED); // creates file from path
bos = new BufferedOutputStream(fos); // creates BOS from FOS
int current = 0; // equals the two integers for comparisons later

try {
    while ((bytesRead = is.read(mybytearray)) != -1) {
        bos.write(mybytearray, 0, bytesRead );
        current += bytesRead;
    }
    bos.flush(); // clears the buffer
    System.out.println("File " + FILE_TO_RECEIVED + " downloaded (" + current + " bytes read)");
} finally {
  bos.close();
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...