com.sheldon.javaPrj.netty.FileServerHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.sheldon.javaPrj.netty.FileServerHandler.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.sheldon.javaPrj.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.stream.ChunkedFile;
import io.netty.handler.stream.ChunkedInput;
import java.io.File;
import java.io.FileOutputStream;

/**
 *
 * @author xiangnan.wang@ipinyou.com
 */
public class FileServerHandler extends SimpleChannelInboundHandler<Object>/*ChannelInboundHandlerAdapter*/ {

    //    @Override
    //    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    //        cause.printStackTrace();
    //        ctx.close();
    //    }
    //
    //    @Override
    //    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    //        super.channelRead(ctx, msg); //To change body of generated methods, choose Tools | Templates.
    //    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("read");
        //        System.out.println(msg);
        ByteBuf bb = (ByteBuf) msg;
        FileOutputStream out = new FileOutputStream(new File("/tmp/test.bk"), false);
        byte[] ba = new byte[bb.readableBytes()];
        bb.readBytes(ba);
        out.write(ba);
        out.flush();
        out.close();
    }

}