在写出了Netty Hello World 和 netty对象传输之后,又觉得不够,看了官网的例子,所以有了现在的这个文件传输。
顺便说下,netty官网的例子真的好,如果要学习netty,还是看官网例子的好。
不过我英文不太好,刚开始走了绕了好大一圈,但是现在熟悉了之后,回过头来看,还是官网的牛X。
在这里再说下netty的零拷贝,这个零拷贝是netty在3.2版本中新加入的功能。
其主要指的是在进行一些比较大的传输比如对象或者文件传输的时候,通过改变数组索引的方式,将数据传输到特定的channel上。
是的channel之间的转换是零拷贝,例如:ByteBuffer和ChannelBuffer
下面就把文件传输的例子贴出来吧。
1、FileClient.java
package filetrans;
import static org.jboss.netty.channel.Channels.pipeline;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
public class FileClient
{
public static void main(String[] args)
{
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory()
{
@Override
public ChannelPipeline getPipeline() throws Exception
{
ChannelPipeline pipeline = pipeline();
pipeline.addLast("decoder", new HttpResponseDecoder());
/*
* 不能添加这个,对传输文件 进行了大小的限制。。。。。
*/
// pipeline.addLast("aggregator", new HttpChunkAggregator(6048576));
pipeline.addLast("encoder", new HttpRequestEncoder());
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("handler", new FileClientHandler());
return pipeline;
}
});
ChannelFuture future = bootstrap.connect(new InetSocketAddress(
"localhost", 8080));
/*
* 这里为了保证connect连接,所以才进行了sleep
* 当然也可以通过future的connect属性判断
*/
try
{
Thread.sleep(3000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
HttpRequest request =