通过Java NiO发送路径

时间:2019-03-26 18:20:29

标签: java sockets nio

我正在对服务器和客户端进行编程,客户端会将文件发送到服务器,但是,我需要一起发送文件名,以便服务器识别并写入客户端发送的名称的文件。当前它不发送文件名,因此我必须将文件名及其保存位置通知服务器。 是否可以发送将保存到文件的文件名和路径? 如果有可能,我应该使用什么代码段来指出此类信息? 如果有人可以帮助我,我真的很感激。

客户端

public class FileSenderClient {
    private void sendFile(SocketChannel socketChannel) throws IOException {
        Path path = Paths.get("C:\\SIS\\database.FDB");\\ path to file 
        FileChannel inChannel = FileChannel.open(path);

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (inChannel.read(buffer) > 0) {
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
        socketChannel.close();
    }
    private SocketChannel CreateChannel() throws IOException {

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(true);
        SocketAddress sockAddr = new InetSocketAddress("localhost", 9000);
        socketChannel.connect(sockAddr);
        return socketChannel;
    }
    public static void main(String[] args) throws IOException {
        FileSenderClient client = new FileSenderClient();
        SocketChannel socketChannel = client.CreateChannel();
        client.sendFile(socketChannel);
    }
}

服务器端

public class FileReceiver {

        private void readFileFromSocketChannel(SocketChannel socketChannel) throws IOException {

        Path path = Paths.get("C:\\Data\\database.FDB"); - here  i need to receive
                                                           the name from the class FileSenderClient
        FileChannel fileChannel = FileChannel.open(path,
                EnumSet.of(StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING,
                        StandardOpenOption.WRITE)
                );
        //Allocate a ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (socketChannel.read(buffer) > 0) {
            buffer.flip();
            fileChannel.write(buffer);
            buffer.clear();
        }
        fileChannel.close();
        System.out.println("Receving file successfully!");
        socketChannel.close();
    }

    private SocketChannel createServerSocketChannel() throws IOException {
        ServerSocketChannel serverSocket = null;
        SocketChannel client = null;
        serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9000));
        client = serverSocket.accept();

        System.out.println("connection established .." + client.getRemoteAddress());
        return client;
    }


    public static void main(String[] args) throws IOException {
        FileReceiver server = new FileReceiver();
        SocketChannel socketChannel = server.createServerSocketChannel();
        server.readFileFromSocketChannel(socketChannel);

    }


}

0 个答案:

没有答案