1. 程式人生 > >《Netty權威指南》(一)簡單的時間服務器P69

《Netty權威指南》(一)簡單的時間服務器P69

通過 adc 不一致 nios pie bound trap 記錄 esp

由於該書是基於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. }



《Netty權威指南》(一)簡單的時間服務器P69