這裡記錄兩個自己寫好的 Netty 範例備查,皆以 netty-3.5.7.Final.jar 搭配 JUnit 測試。
package com.wujintao.netty;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.junit.Test;
class HelloWorldServerHandler extends SimpleChannelHandler {
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
e.getChannel().write("Hello, World");
}
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
System.out.println("Unexpected exception from downstream." + e.getCause());
e.getChannel().close();
}
}
class HelloWorldClientHandler extends SimpleChannelHandler {
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
String message = (String) e.getMessage();
System.out.println(message);
e.getChannel().close();
}
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
System.out.println("Unexpected exception from downstream." + e.getCause());
e.getChannel().close();
}
}
/**
* Netty 與 Mina 的差異:
* Netty 基於 Pipeline 處理,Mina 基於 Filter 過濾;
* Netty 的事件驅動模型具有更好的擴展性與易用性;
* 對 HTTPS、SSL、PB、RSTP、Text & Binary 等協議支援完整;
* 官方測試顯示 Netty 在 UDP 傳輸與整體效能上優於 Mina。
*/
public class TestCase {
public void testServer() {
// 初始化 channel 的輔助類
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new HelloWorldServerHandler());
return pipeline;
}
});
// 監聽 8080,接收連線請求
bootstrap.bind(new InetSocketAddress(8080));
}
public void testClient() {
// 建立客戶端 channel 的輔助類,發起連線
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// 同一個 Handler 實例若被多個 Channel 共用會導致資料錯亂,
// 因此必須透過 ChannelPipelineFactory 為每個 Channel 建立獨立 pipeline
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new HelloWorldClientHandler());
return pipeline;
}
});
ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8080));
future.getChannel().getCloseFuture().awaitUninterruptibly();
bootstrap.releaseExternalResources();
}
@Test
public void testNetty() {
testServer();
testClient();
}
}
這段程式最值得注意的是註解裡提到的那點:Handler 實例不應跨 Channel 共用,務必透過 ChannelPipelineFactory 為每個連線產生全新的 pipeline,否則多執行緒下資料會互相污染。另外別忘了 releaseExternalResources() 釋放執行緒池。
第二個範例請見下一頁:Netty 使用實例(二)