代码拉取完成,页面将自动刷新
上一篇<<初识Netty>>, 我们讲解了如何用Netty实现一个WebSocket服务端,作为实时聊天室的服务器. 本文的场景是, 我们已经有一个SpringBoot的Web服务了, 希望将WebSocket的能力整合到SpringBoot开发的Web服务中,也就是随着Web服务的启动而启动, 随着Web服务的关闭而关闭.
ContextRefreshedEvent : 上下文刷新事件是在 Spring 应用上下文(ApplicationContext)刷新之后发送。 Spring Boot 启动事件顺序
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class NettyStartListener implements ApplicationListener<ContextRefreshedEvent> {
@Resource
private WebSocketNettyServer webSocketNettyServer;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
try {
webSocketNettyServer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
除了 WebSocketNettyServer, 还需要 ChatHandler / WebSocketChannelInitializer, 这两个跟上一篇文章内容的编码完全一样, 懒得搬了, 有需要自己去找下吧. <<Netty基于WebSocket实现的简单聊天室>>
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;
@Component
public class WebSocketNettyServer {
// Netty服务器启动对象
private final ServerBootstrap serverBootstrap;
public WebSocketNettyServer() {
serverBootstrap = new ServerBootstrap();
// 初始化服务器启动对象
// 主线程池
NioEventLoopGroup mainGrp = new NioEventLoopGroup();
// 从线程池
NioEventLoopGroup subGrp = new NioEventLoopGroup();
serverBootstrap
// 指定使用上面创建的两个线程池
.group(mainGrp, subGrp)
// 指定Netty通道类型
.channel(NioServerSocketChannel.class)
// 指定通道初始化器用来加载当Channel收到事件消息后,
// 如何进行业务处理
.childHandler(new WebSocketChannelInitializer());
}
public void start() {
// 绑定服务器端口,以异步的方式启动服务器
ChannelFuture future = serverBootstrap.bind(9090);
}
}
客户端1: 客户端2: 服务端运行日志:
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。