《Netty权威指南》(一)简单的时间服务器P69

由于该书是基于Netty5编写的样例代码,而Netty5已经被官方废弃。
目前基于推荐版的4.1.12.Final在学习过程中,可能会出现个别接口不一致的情况。所以记录可在4.1.12下编译通过的代码

  1. package net.xjdsz.n;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.*;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioServerSocketChannel;
  9. import java.util.Date;
  10. /**
  11. * Created by dingshuo on 2017/6/14.
  12. */
  13. public class TimeServer {
  14. public void bind(int port) throws Exception{
  15. EventLoopGroup bossGroup=new NioEventLoopGroup();
  16. EventLoopGroup workerGroup=new NioEventLoopGroup();
  17. try{
  18. ServerBootstrap b=new ServerBootstrap();
  19. b.group(bossGroup,workerGroup)
  20. .channel(NioServerSocketChannel.class)
  21. .option(ChannelOption.SO_BACKLOG,1024)
  22. .childHandler(new ChannelInitializer<SocketChannel>() {
  23. @Override
  24. protected void initChannel(SocketChannel socketChannel) throws Exception {
  25. socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
  26. @Override
  27. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  28. ByteBuf buf=(ByteBuf)msg;
  29. byte[] req=new byte[buf.readableBytes()];
  30. buf.readBytes(req);
  31. String body=new String(req,"UTF-8");
  32. System.out.println("收到数据:"+body);
  33. String currentTime=new Date(System.currentTimeMillis()).toString();
  34. ByteBuf resp= Unpooled.copiedBuffer(currentTime.getBytes());
  35. ctx.write(resp);
  36. }
  37. @Override
  38. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  39. ctx.flush();
  40. }
  41. @Override
  42. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  43. ctx.close();
  44. }
  45. });
  46. }
  47. });
  48. //绑定端口,同步等待成功
  49. ChannelFuture f=b.bind(port).sync();
  50. //等待服务端监听端口关闭
  51. f.channel().closeFuture().sync();
  52. }finally {
  53. //退出,释放资源
  54. bossGroup.shutdownGracefully();
  55. workerGroup.shutdownGracefully();
  56. }
  57. }
  58. public static void main(String[] args) throws Exception{
  59. TimeServer timeServer=new TimeServer();
  60. timeServer.bind(2000);
  61. }
  62. }



posted @ 2017-06-14 17:29  二刀  阅读(306)  评论(0编辑  收藏  举报