前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Netty入门学习系列--helloworld服务端(一)

Netty入门学习系列--helloworld服务端(一)

作者头像
用户1257393
发布2018-07-30 15:05:20
2750
发布2018-07-30 15:05:20
举报
文章被收录于专栏:精讲JAVA精讲JAVA

netty服务端

结合上面几篇文章,我们大体了解了netty使用的nio的原理,但是编写一个通信,使用nio过于复杂,对于我们来说,快捷使用nio通信变得尤为重要,于是,我们的主角netty出现了,简化原生nio开发。

public class NettyServerTest {

代码语言:javascript
复制
public static void main(String [] args){
    new NettyServerTest().bing();
}
private void bing(){
    EventLoopGroup bossgroup = new NioEventLoopGroup();
    EventLoopGroup workgroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossgroup,workgroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG,1024).childHandler(new NettyChildHandle());
    try {
        ChannelFuture cf = serverBootstrap.bind(9999).sync();
        cf.channel().closeFuture().sync();
    } catch (InterruptedException ignored) {
    } finally {
        bossgroup.shutdownGracefully();
        workgroup.shutdownGracefully();
    }
}
private class NettyChildHandle extends ChannelInitializer<socketchannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new NettyServerHandle());
    }
}}
NettyServerHandle用来处理通信请求,最主要的是实现里面的channelRead、channelReadComplete、exceptionCaught三个方法

public class NettyServerHandle extends ChannelInboundHandlerAdapter {

代码语言:javascript
复制
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf byteBuf = (ByteBuf) msg;
    byte [] bytes = new byte[byteBuf.readableBytes()];
    byteBuf.readBytes(bytes);
    String body = new String(bytes,"UTF-8");
    System.out.println("收到来自外星的命令"+body);
    String currentTime = "hello".equals(body)?"my name is netty":"No";
    ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
    ctx.write(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
     ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
}}
截止目前,netty的服务端编写完成。,下一篇编写客户端,客户端相对来说较为简单
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-05-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 精讲JAVA 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • netty服务端
    • 结合上面几篇文章,我们大体了解了netty使用的nio的原理,但是编写一个通信,使用nio过于复杂,对于我们来说,快捷使用nio通信变得尤为重要,于是,我们的主角netty出现了,简化原生nio开发。
      • NettyServerHandle用来处理通信请求,最主要的是实现里面的channelRead、channelReadComplete、exceptionCaught三个方法
        • 截止目前,netty的服务端编写完成。,下一篇编写客户端,客户端相对来说较为简单
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档