吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1969|回复: 2
收起左侧

[Java 转载] 基于Netty实现简易高并发IM

[复制链接]
spring_cloud 发表于 2021-4-1 17:00
netty服务public class NettyServer {

    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);

    private static class SingletionWSServer {
        static final NettyServer instance = new NettyServer();
    }

    public static NettyServer getInstance() {
        return SingletionWSServer.instance;
    }

    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;
    private ServerBootstrap server;
    private ChannelFuture future;

    public NettyServer() {
        mainGroup = new NioEventLoopGroup();
        subGroup = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyChannelInitializer());
    }

    public void start(int port) {
        this.future = server.bind(port);
        log.info("netty server start success");
    }

}管道初始化public class NettyChannelInitializer extends ChannelInitializer<SocketChannel>{

   private static final Logger log = LoggerFactory.getLogger(NettyChannelInitializer.class);
   
   @Override
   protected void initChannel(SocketChannel ch) throws Exception {
      log.info(" init  channel ....");
      ChannelPipeline pipeline = ch.pipeline();
      // websocket 基于http协议,所以要有http编解码器
      pipeline.addLast("HttpServerCodec",new HttpServerCodec());
         
      // 对写大数据流的支持   
      pipeline.addLast(new ChunkedWriteHandler());
      
      // httpMessage进行聚合,聚合成FullHttpRequestFullHttpResponse
      // 几乎在netty中的编程,都会使用到此hanler
      pipeline.addLast(new HttpObjectAggregator(1024*64));
      
      
      // 增加心跳支持 start
      // 针对客户端,如果在1分钟时没有向服务端发送读写心跳(ALL),则主动断开
      // 如果是读空闲或者写空闲,不处理
      pipeline.addLast(new IdleStateHandler(8, 10, 12));
      // 自定义的空闲状态检测
      pipeline.addLast(new NettyWsChannelInboundHandler());
      
      // 以下是支持httpWebsocket
      /**
       * websocket 服务器处理的协议,用于指定给客户端连接访问的路由 : /ws
       * handler会帮你处理一些繁重的复杂的事
       * 会帮你处理握手动作: handshakingclose, ping, pongping + pong = 心跳
       * 对于websocket来讲,都是以frames进行传输的,不同的数据类型对应的frames也不同
       */
      pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
         
      // 自定义的wshandler
      pipeline.addLast(new NettyWsChannelInboundHandler());
         
      // 自定义 http
      pipeline.addLast(new NettyHttpChannelInboundHandler());
   }

}未完待续....

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

alan3258 发表于 2021-4-1 18:19
这是实例还是真正支持高并发?没看到高并发的地方啊。
52changew 发表于 2021-4-1 18:19
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-12 15:03

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表