SpringBoot优雅整合Netty实现WebSocket通信(初学者友好)
温馨提示:
本文最后更新于 2025年07月18日,已超过 8 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
本文是为 Java 后端初学者 精心准备的一份图文教程,带你一步一步用 SpringBoot + Netty 搭建一个稳定高效的 WebSocket 实时通信服务。真正做到从零基础快速掌握核心实现原理和实战技巧。
✨ 为什么选择 Netty 来实现 WebSocket?
在实际开发中,我们常见的 WebSocket 实现方式包括使用 Spring 自带的 @ServerEndpoint
、Tomcat 容器、SockJS 等。然而,当你需要面对更高并发、灵活处理底层连接、实现更优的性能扩展性时,Netty + SpringBoot 是一个更加优秀的选择。
✅ Netty 的优势:
- 高性能 NIO 网络框架
- 灵活可定制,适合底层网络协议开发
- 更精细的连接管理、数据处理控制
🧱 技术准备
- Java 8+
- Spring Boot 2.x
- Netty 4.x
- Maven
- IDE:IntelliJ IDEA 或 Eclipse
📦 项目结构预览
├── WebSocketNettyApplication.java
├── config/
│ └── NettyConfig.java
├── netty/
│ ├── WebSocketServer.java
│ ├── WebSocketChannelInitializer.java
│ └── WebSocketHandler.java
`
🧩 第一步:创建 SpringBoot 项目并添加依赖
在 pom.xml
中添加 Netty 依赖:
<dependencies>
<!-- Spring Boot 核心依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Netty 核心 -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.86.Final</version>
</dependency>
</dependencies>
🔧 第二步:编写 Netty 服务端配置
NettyConfig.java
@Configuration
public class NettyConfig {
@Value("${netty.port}")
private int port;
@Bean
public WebSocketServer webSocketServer() {
return new WebSocketServer(port);
}
@EventListener(ApplicationReadyEvent.class)
public void start() {
webSocketServer().start();
}
}
application.yml 配置:
netty:
port: 8081
🧠 第三步:实现 WebSocket 服务核心逻辑
WebSocketServer.java
public class WebSocketServer {
private final int port;
public WebSocketServer(int port) {
this.port = port;
}
public void start() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new WebSocketChannelInitializer());
Channel ch = bootstrap.bind(port).sync().channel();
System.out.println("WebSocket Server started at port " + port);
ch.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
WebSocketChannelInitializer.java
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new WebSocketHandler());
}
}
WebSocketHandler.java
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
System.out.println("接收到客户端消息:" + msg.text());
ctx.channel().writeAndFlush(new TextWebSocketFrame("服务端响应:" + msg.text()));
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
System.out.println("客户端连接:" + ctx.channel().id().asLongText());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
System.out.println("客户端断开连接:" + ctx.channel().id().asLongText());
}
}
🔍 第四步:启动项目进行测试
- 启动 SpringBoot 项目。
使用浏览器或 WebSocket 客户端(如:Postman、websocat、Socket.IO)连接地址:
ws://localhost:8081/ws
- 发送消息,查看控制台与返回结果。
扩展
客户端(微信小程序)
wxml
<view>接收的消息</view>
<textarea style="border: 1px solid black;" value="{{msg}}"></textarea>
<view>发送的消息</view>
<textarea style="border: 1px solid black;" bindinput='inputTitle'></textarea>
<button style="border: 1px solid violet;" bindtap='send'>发送消息</button>
<button style="border: 1px solid red;" bindtap='openWebSocket'>打开WebSocket连接</button>
<button style="border: 1px solid red;" bindtap='closeWebSocket'>关闭WebSocket连接</button>
js
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 绑定参数
*/
inputTitle: function(e){
var _this = this;
_this.setData({ title: e.detail.value })
},
/**
* 发送信息
*/
send: function(){
var _this = this;
wx.sendSocketMessage({
data: _this.data.title ,
success: (result) => {
console.log(result)
},
fail: (result) => {
console.log(result)
wx.showToast({
title: result.errMsg,
icon:"none",
duration:5000
})
},
})
},
/**
* 打开连接
*/
openWebSocket: function(){
//创建一个 WebSocket 连接
wx.connectSocket({
url: 'ws://10.8.51.124:8000/ws',
success: (result) => {
console.log(result)
},
})
//监听 WebSocket 连接打开事件
wx.onSocketOpen(function (result) {
console.log(result)
})
//监听 WebSocket 错误事件
wx.onSocketError(function (result) {
console.log(result)
wx.showToast({
title: result.errMsg,
})
})
//监听 WebSocket 接受到服务器的消息事件
wx.onSocketMessage((result) => {
console.log(result)
this.setData({
msg: result.data
})
})
//监听 WebSocket 关闭事件
wx.onSocketClose((result) => {
console.log(result)
})
},
/**
* 关闭连接
*/
closeWebSocket: function(){
wx.closeSocket({
success: (result) => {
console.log(result)
},
})
}
})
📚 适合延伸阅读
🧾 总结
本文介绍了如何使用 SpringBoot 与 Netty 组合,手动实现一个 WebSocket 服务。相比于传统框架,Netty 提供了更灵活的连接管理能力与更高性能,适合构建 IM 聊天、实时通知、游戏服务等高并发实时系统。
🚀 你可以这样做练手!
- 支持私聊与群聊
- 自定义消息格式(JSON)
- 心跳检测与重连机制
- 与前端 Vue/React WebSocket 客户端对接
SEO 关键词:SpringBoot整合Netty, WebSocket实现方法, Java后端教程
SEO 描述:一步步教你如何用SpringBoot整合Netty实现WebSocket通信,初学者也能轻松掌握!
💡 如果这篇教程对你有帮助,别忘了点个赞 👍 或分享给正在学习 Java 后端开发的朋友!
正文到此结束
- 本文标签: Java Spring Boot SpringBoot整合Netty
- 本文链接: https://code.itptg.com/article/37
- 版权声明: 本文由老魏原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权