摘要:pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true));
以下是使用Spring Boot、Netty、Vue和Websocket实现在线聊天的分步指南:
一、后端实现(Spring Boot + Netty)
1. 创建Spring Boot项目
io.netty
netty-all
4.1.68.Final
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 {
@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 {
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
{{ msg }}
Send
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;
}
}
三、运行步骤
启动Spring Boot应用bash
mvn spring-boot:run
启动Vue应用bash
npm run serve
访问 (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
// 在前端vue.config.js中配置代理
module.exports = {
devServer: {
proxy: {
'/ws': {
target: 'http://localhost:8080',
ws: true
}
}
}
}
使用Netty处理底层WebSocket通信支持高并发连接前后端分离架构实时双向通信可扩展性强可以通过添加更多Handler实现消息类型分发、心跳检测、流量控制等高级功能。
来源:老客数据一点号