简单的Netty处理程序,逐字节迭代消息

时间:2012-03-14 18:33:28

标签: java netty

是否有一个非常简单的Netty处理程序的例子,它只是简单地获取在线上发送的任何数据并将其写入文件?

我在考虑这个问题:

public class SimpleHandler extends SimpleChannelUpstreamHandler {

public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        HttpRequest request = (HttpRequest) e.getMessage();
        // get data from request and write to a file
}

有什么想法吗?谢谢你的任何想法

2 个答案:

答案 0 :(得分:4)

您也可以使用此方法将ChannelBuffer的内容传输到OutputStream:

http://netty.io/docs/stable/api/org/jboss/netty/buffer/ChannelBuffer.html#readBytes(java.io.OutputStream,%20int

这样的事情:

public class FileWriterHandler extends SimpleChannelHandler {
    private final String filename;

    public FileWriterHandler(String filename) {
        this.filename = filename;
    }

    @Override
    public void messageReceived(ChannelHandlerContext context, MessageEvent event) throws Exception{
        ChannelBuffer buffer = (ChannelBuffer)event.getMessage();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filename, true)
            buffer.readBytes(out, buffer.readableBytes());
        } finally {
            if (out != null) out.close();
        }
    }
}   

答案 1 :(得分:2)

我写了其中一篇用于测试一段时间:

public class FileWriterHandler extends SimpleChannelHandler {
    private final String filename;

    public FileWriterHandler(String filename) {
        this.filename = filename;
    }

    @Override
    public void messageReceived(ChannelHandlerContext context, MessageEvent event) {
        ChannelBuffer buffer = (ChannelBuffer)event.getMessage();
        byte[] bytes = new byte[buffer.readableBytes()];
        buffer.readBytes(bytes);
        try {
            DataOutputStream stream = new DataOutputStream(new FileOutputStream(filename, true));
            stream.write(bytes, 0, bytes.length);
            stream.flush();
            stream.close();
        } catch (IOException ex) {
            throw runtime(ex);
        }
    }
}

这只是为了测试,因此我只是重新抛出异常而不是真正正确处理它们。希望这有帮助。

您可以按照以下方式进行设置:

ServerBootstrap bootstrap = initializedSomehow();
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() {
        return pipeline(new FileWriterHandler("yourfile.txt"));
    }
});