在前几篇中,我们完成了netty和springboot的整合,大致领略了一下netty作为web通讯服务器的魅力,据我所知,netty在不少做聊天应用型的公司里面使用很广泛,主要还是得益于netty底层的实现原理对于高并发性能的良好支持和扩展,以及netty可定制化的API组件和其成熟的使用场景,当然,你也可以选择使用诸如socketJS或者原生的socket来实现聊天的功能,但总体来说都不如netty使用灵活,下面就以springboot整合netty实现一个简单的单聊功能;
首先,在实现功能之前我们先了解一下netty的API中有一个很重要的组件叫做,Handler,在netty服务器的实现中,handler是一个很重要的组件,通俗来说,handler相当于是我们处理客户端消息的一个助手类,或者叫做业务逻辑的补充实现类更贴切,因为netty底层使用的是nio模型,里面有个channel的玩意,
说白了,当netty服务器启动之后,整合交互过程大致是这样,
1、客户端连接成功,netty创建一个和客户端通信的channel,客户端发消息给服务端并不是直接发给服务端,而是发送到channel中,更多的客户端连接服务端时,netty