zoukankan      html  css  js  c++  java
  • 《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. }



  • 相关阅读:
    ABAP-FI-Redirection of read accesses from ANEA to FAAV_ANEA failed
    招聘
    五分钟教你在长沙如何找到靠谱的驾校和教练(长沙找驾校)
    数组哪些方法能改变原数组,以及循环改变数组的情况
    FXGL游戏开发-JavaFX游戏框架
    tempermonkey.d.ts | 油猴函数类型
    post导出文件
    mescroll.js 使用
    查看托管应用池用法
    IDEA配置
  • 原文地址:https://www.cnblogs.com/tilv37/p/7010009.html
Copyright © 2011-2022 走看看