Skip to content

Instantly share code, notes, and snippets.

@ezhov-da
Last active March 10, 2019 12:16
Show Gist options
  • Save ezhov-da/496414549be6cd514169e921187eb172 to your computer and use it in GitHub Desktop.
Save ezhov-da/496414549be6cd514169e921187eb172 to your computer and use it in GitHub Desktop.
передача файлов между сервером и клиентом
package ru.ezhov.fileserver;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.logging.Logger;
//https://ru.stackoverflow.com/questions/813450/%d0%9f%d0%b5%d1%80%d0%b5%d0%b4%d0%b0%d1%87%d0%b0-%d1%84%d0%b0%d0%b9%d0%bb%d0%be%d0%b2-nio2
public class NioServer {
private static final Logger LOG = Logger.getLogger(NioServer.class.getName());
private static final int PORT = 55555;
private static final String FILE_PATH = "E:\\test-java.java";
public static void main(String[] args) {
try {
try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
serverSocketChannel.bind(new InetSocketAddress(PORT));
try (SocketChannel socketChannel = serverSocketChannel.accept()) {
try (FileChannel fileChannel =
FileChannel.open(
Paths.get(FILE_PATH),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE
)
) {
fileChannel.transferFrom(socketChannel, 0, Long.MAX_VALUE);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class NioClient {
private static final int PORT = 55555;
private static final String HOST = "localhost";
private static final String FILE_NAME = "SOURCE";
public static void main(String args[]) {
try {
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);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment