您的位置:首页 > 其它

Netty 简单样例分析

2019-06-12 20:39 78 查看

Netty 是JBoss旗下的io传输的框架,他利用java里面的nio来实现高效,稳定的io传输。

作为io传输,就会有client和server,下面我们看看用netty怎样写client和server

Client:
需要做的事情:

  1. 配置client启动类
    ClientBootstrap bootstrap = new ClientBootstrap(…)

  2. 根据不同的协议或者模式为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() = true |
  • | Uncompleted | | +===========================+
  • ±-------------------------+ | | Completed with failure |
  • | isDone() = false | | ±--------------------------+
  • | isSuccess() = false |----±—> isDone() = true |
  • | isCancelled() = false | | | getCause() = non-null |
  • | getCause() = null | | +===========================+
  • ±-------------------------+ | | Completed by cancellation |
  • |    +---------------------------+
  • +---->      isDone() = <b>true</b>      |
  • | isCancelled() = <b>true</b>      |
  • +---------------------------+
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: