码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2017-06-14 18:06:51      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:channel   不一致   指南   creat   object   []   new   elf   pool   

由于该书是基于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

标签:channel   不一致   指南   creat   object   []   new   elf   pool   

原文地址:http://www.cnblogs.com/tilv37/p/7010009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!