如何使用netty传输文件?

时间:2014-09-09 12:33:48

标签: java file netty transfer

我是Netty的新手。虽然我已经学习了基础知识,但在尝试使用Netty传输文件时遇到了问题。在客户端中创建文件,但没有数据从服务器传输到客户端。请在下面找到我的代码并帮我修复它:

Client.java

        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new ClientInitializer(sslCtx));

        Channel ch = b.connect(HOST, PORT).sync().channel();

        ChannelFuture lastWriteFuture = null;

         if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }

ClientInitializer.java

    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));

    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new ClientHandler());

ClientHandler.java

public void messageReceived(ChannelHandlerContext ctx, String msg) {
    System.err.println(msg+" THIS IS PRINTED");
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.close();
}

protected void channelRead0(ChannelHandlerContext arg0, String arg1)
        throws Exception {
     System.err.println(arg1);
}

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg)
        throws Exception {

    Channel chanbuf = ctx.channel().read();
    ByteBuf chan = ctx.read().alloc().buffer();
    byte[] bytes = new byte[chan.readableBytes()];
    chan.readBytes(bytes);
     FileOutputStream out = new FileOutputStream("D:/test.txt");
     ObjectOutputStream oout = new ObjectOutputStream(out);
     System.out.println("HEY"+chan.readableBytes());

     oout.write(bytes, 0, bytes.length);

     oout.close();
    }

Server.java

    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new ServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();

    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

ServerInitializer.java

    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());


    pipeline.addLast(new ServerHandler());

ServerHandler.java

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
            new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(Future<Channel> future) throws Exception {

                RandomAccessFile toFile = new RandomAccessFile("D:/Received.zip", "rw");
                    toFile.length();
                if(future.isSuccess())
                    {
                        FileChannel toChannel = toFile.getChannel();
                        for (Channel c: channels) {
                        if(c != ctx.channel())
                        {
                        c.writeAndFlush(new DefaultFileRegion(toChannel, 0, toFile.length()));
                        }
                        }
                    System.err.print("HIoperationComplete");    
                    }
                    ctx.writeAndFlush(
                            "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n");
                    ctx.writeAndFlush(
                            "Your session is protected by " + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() +
                            " cipher suite.\n");

                    channels.add(ctx.channel());
                }
            });
}

提前致谢!!!

0 个答案:

没有答案