SpringBoot+Netty+Vue实现在线聊天
以下是使用Spring Boot、Netty、Vue和WebSocket实现在线聊天的分步指南:
一、后端实现(Spring Boot + Netty)
1. 创建Spring Boot项目
xml
<!-- pom.xml 关键依赖 -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.68.Final</version>
</dependency>
2. Netty WebSocket服务器配置
java
// WebSocketServer.java
public class WebSocketServer {
private final int port;
public WebSocketServer(int port) {
this.port = port;
}
public void start() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new WebSocketInitializer());
Channel channel = bootstrap.bind(port).sync().channel();
System.out.println("WebSocket server started on port: " + port);
channel.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
3. 通道初始化配置
java
// WebSocketInitializer.java
public class WebSocketInitializer 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", null, true));
pipeline.addLast(new TextWebSocketFrameHandler());
}
}
4. 消息处理器
java
// TextWebSocketFrameHandler.java
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
public void channelActive(ChannelHandlerContext ctx) {
channels.add(ctx.channel());
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
String request = frame.text();
channels.writeAndFlush(new TextWebSocketFrame(request));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
cause.printStackTrace();
}
}
5. Spring Boot启动类
java
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
new WebSocketServer(8080).start();
}
}
二、前端实现(Vue.js)
1. 创建Vue项目
bash
vue create chat-client
2. 聊天组件
vue
<!-- Chat.vue -->
<template>
<div>
<div class="chat-box">
<div v-for="(msg, index) in messages" :key="index">{{ msg }}</div>
</div>
<input v-model="message" @keyup.enter="sendMessage">
<button @click="sendMessage">Send</button>
</div>
</template>
<script>
export default {
data() {
return {
message: '',
messages: [],
socket: null
}
},
mounted() {
this.socket = new WebSocket('ws://localhost:8080/ws');
this.socket.onopen = () => {
console.log('WebSocket connected');
};
this.socket.onmessage = (event) => {
this.messages.push(event.data);
};
this.socket.onclose = () => {
console.log('WebSocket disconnected');
};
},
methods: {
sendMessage() {
if (this.message.trim()) {
this.socket.send(this.message);
this.message = '';
}
}
},
beforeDestroy() {
this.socket.close();
}
}
</script>
三、运行步骤
- 启动Spring Boot应用
bash
mvn spring-boot:run
- 启动Vue应用
bash
npm run serve
- 访问 http://localhost:8081 (Vue默认端口)
四、功能扩展建议
- 消息协议增强(JSON格式):
json
{
"type": "message",
"content": "Hello",
"sender": "user123",
"timestamp": 1625097600000
}
- 用户认证:
java
// 在WebSocket握手前进行认证
pipeline.addLast(new HttpRequestHandler());
- 消息持久化:
java
// 在消息处理时保存到数据库
@Autowired
private MessageRepository messageRepository;
public void saveMessage(ChatMessage message) {
messageRepository.save(message);
}
五、关键配置说明
- Netty配置参数:
java
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
- WebSocket路径配置:
java
new WebSocketServerProtocolHandler("/ws", null, true)
- 跨域处理(开发环境):
java
// 在前端vue.config.js中配置代理
module.exports = {
devServer: {
proxy: {
'/ws': {
target: 'http://localhost:8080',
ws: true
}
}
}
}
该实现方案特点:
- 使用Netty处理底层WebSocket通信
- 支持高并发连接
- 前后端分离架构
- 实时双向通信
- 可扩展性强
可以通过添加更多Handler实现消息类型分发、心跳检测、流量控制等高级功能。