Good afternoon there is a code

SocketAddress socketAddress = new InetSocketAddress(HOST, PORT); SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(socketAddress); FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel(); fileChannel.transferTo(0, fileChannel.size(), socketChannel); 

as I understand it to transfer the file. You need the appropriate code from the recipient. I also wanted to ask that you can transfer videos, pictures, archives in this way. If not, please give a link to the resource where you can read about it.

    1 answer 1

    Server receiving file:

     public class NioServer { private static final int PORT = 1234; private static final String FILE_NAME = "image.jpg"; public static void main(String args[]) throws IOException { try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) { serverSocketChannel.bind(new InetSocketAddress(PORT)); try (SocketChannel socketChannel = serverSocketChannel.accept()) { try (FileChannel fileChannel = FileChannel.open(Paths.get(FILE_NAME), StandardOpenOption.CREATE, StandardOpenOption.WRITE)) { fileChannel.transferFrom(socketChannel, 0, Long.MAX_VALUE); } } } } } 

    Client sending file:

     public class NioClient { private static final int PORT = 1234; private static final String HOST = "localhost"; private static final String FILE_NAME = "image.jpg"; public static void main(String args[]) throws IOException { InetSocketAddress serverAddress = new InetSocketAddress(HOST, PORT); try (SocketChannel socketChannel = SocketChannel.open(serverAddress)) { try (FileChannel fileChannel = FileChannel.open(Paths.get(FILE_NAME))) { fileChannel.transferTo(0, fileChannel.size(), socketChannel); } } } } 

    In this way, you can transfer videos, pictures and archives.

    • Good evening, my task is to make possible the transfer of files from the server to the client and back. I added your code if you run the code separately (transfer the file from the server -> to the client after launching the transfer separately (client -> to server). Everything works fine. But I didn’t specify the combination. As I understand it on the server and client which is responsible for accepting the file should be in a separate stream in both classes. The file transfer code in both classes should also be in separate streams. Due to dubbing of the lines it blocks the stream. And the code itself is duplicated.
    • Ask a new question, describe in detail what you are trying to achieve and what does not work. - Sergey Gornostaev