4

I'm new to Netty. Though I have learnt the basics, I face issues when trying to transfer a file using Netty. A file gets created in the client but no data is transferred to client from server. Please find my code below and help me fix it:

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());
                }
            });
}

Thanks in advance!!!

user1395264
  • 143
  • 3
  • 18
  • I'm just guessing but it seems you are sending the file to every channel BUT the freshly connected one `if(c != ctx.channel())`. – Moh-Aw Sep 10 '14 at 06:43
  • 1
    Netty has a few examples which cover the use case you describe. [HTTP file serving](https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/http/file) and [non http file server](https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/file). I suggest using these as a template and make adjustments as needed. – Scott Mitchell Nov 08 '14 at 08:34
  • I have tried to make adjustments to the samples but I wasnt successful. Can anyone help me with some sample of server and client to transfer file from server to client? – user1395264 Jan 30 '15 at 10:57
  • @user1395264 Hi, did you solve your task? – Antonio Nov 30 '16 at 14:20
  • @ScottMitchell can you make your examples available? – SGuru Oct 25 '18 at 21:26

0 Answers0