Netty 是JBoss旗下的io传输的框架,他利用java里面的nio来实现高效,稳定的io传输。
作为io传输,就会有client和server,下面我们看看用netty怎样写client和server
Client:
需要做的事情:
-
配置client启动类
ClientBootstrap bootstrap = new ClientBootstrap(..) -
根据不同的协议或者模式为client启动类设置pipelineFactory。
这里telnet pipline Factory 在netty中已经存在,所有直接用
bootstrap.setPipelineFactory(new TelnetClientPipelineFactory());
也可以自己定义
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(
new DiscardClientHandler(firstMessageSize));
}
});
这里DiscardClientHandler 就是自己定义的handler,他需要
public class DiscardServerHandler extends SimpleChannelUpstreamHandler 继承SimpleChannelUpstreamHandler 来实现自己的handler。这里DiscardClientHandler
是处理自己的client端的channel,
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
// Server is supposed to send nothing. Therefore, do nothing.
}
可以看到Discard client不需要接受任何信息
3.连接server
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
这里解释一下channelFuture:
在Netty中所有的io操作都是异步的,这也就是意味任何io访问,那么就立即返回处理,并且不能确保
返回的数据全部完成。因此就出现了channelFuture,channelFuture在传输数据时候包括数据和状态两个
部分。他只有Uncompleted和Completed
+---------------------------+
| Completed successfully |
+---------------------------+
+----> isDone() = <b>true</b> |
- +--------------------------+ | | isSuccess() = <b>true</b> |
- | Uncompleted | | +===========================+
- +--------------------------+ | | Completed with failure |
- | isDone() = <b>false</b> | | +---------------------------+
- | isSuccess() = false |----+----> isDone() = <b>true</b> |
- | isCancelled() = false | | | getCause() = <b>non-null</b> |
- | getCause() = null | | +===========================+
- +--------------------------+ | | Completed by cancellation |
| +---------------------------+
+----> isDone() = <b>true</b> |
| isCancelled() = <b>true</b> |
+---------------------------+
网友评论