当前位置:首页 > 技术分析 > 正文内容

SpringBoot+Netty+Vue实现在线聊天

ruisui881周前 (04-22)技术分析12

以下是使用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>

三、运行步骤

  1. 启动Spring Boot应用

bash

mvn spring-boot:run

  1. 启动Vue应用

bash

npm run serve

  1. 访问 http://localhost:8081 (Vue默认端口)

四、功能扩展建议

  1. 消息协议增强(JSON格式):

json

{

"type": "message",

"content": "Hello",

"sender": "user123",

"timestamp": 1625097600000

}

  1. 用户认证:

java

// 在WebSocket握手前进行认证

pipeline.addLast(new HttpRequestHandler());

  1. 消息持久化:

java

// 在消息处理时保存到数据库

@Autowired

private MessageRepository messageRepository;


public void saveMessage(ChatMessage message) {

messageRepository.save(message);

}

五、关键配置说明

  1. Netty配置参数:

java

.option(ChannelOption.SO_BACKLOG, 128)

.childOption(ChannelOption.SO_KEEPALIVE, true)

  1. WebSocket路径配置:

java

new WebSocketServerProtocolHandler("/ws", null, true)

  1. 跨域处理(开发环境):

java

// 在前端vue.config.js中配置代理

module.exports = {

devServer: {

proxy: {

'/ws': {

target: 'http://localhost:8080',

ws: true

}

}

}

}

该实现方案特点:

  • 使用Netty处理底层WebSocket通信
  • 支持高并发连接
  • 前后端分离架构
  • 实时双向通信
  • 可扩展性强

可以通过添加更多Handler实现消息类型分发、心跳检测、流量控制等高级功能。

扫描二维码推送至手机访问。

版权声明:本文由ruisui88发布,如需转载请注明出处。

本文链接:http://www.ruisui88.com/post/3519.html

标签: vue跨域
分享给朋友:

“SpringBoot+Netty+Vue实现在线聊天” 的相关文章

「 VUE3 + TS + Vite 」父子组件间如何通信?

组件之间传值,大家都很熟悉,涉及到 VUE3 +TS 好多同学就无从下手了,所以分享这篇文章,希望看完后提起 VUE3+TS 能够不慌不忙。平时使用的函数如:ref、reactive、watch、computed 等需要先引入才能使用,但是本篇文章介绍的 defineProps、withDefaul...

前后端分离自动化运维平台开发

运维平台采用前后端分离:前端vue,框架vue-element-admin;后端python,框架django-rest-framework.目前运维平台模块如下:1、 CMDB管理应用管理、环境管理、开发语言管理、产品项目管理、资产管理2、 构建发布持续构建、持续部署、Jar工程依赖构建3、 容器...

Gitlab之间进行同步备份

目前,我们公司有两个研发团队,分别在北京和武汉,考虑到访问速度的问题,原有武汉的研发环境在近端部署。也就是北京和武汉分别有两套独立的研发管理环境,虽然这解决了近端访问速度的问题,但是管理上较为分散,比如研发环境备份和恢复就是最重要的问题之一。最近,处于对安全性和合规性的考虑,希望将北京和武汉的源代码...

雅马哈TMAX 560 TECH MAX 外媒深度测评

应雅马哈(Yamaha)的邀请,在葡萄牙埃斯托里尔对全新的Yamaha TMAX 560 Tech Max踏板车进行了测试,在这里TMAX 560 Tech Max售价为11649英镑。雅马哈TMAX长期以来一直站在踏板车的顶端,就声誉和知名度而言,它是当之无愧的大踏板界NO.1。2020 TMAX...

三维家-系统快捷键使用

快键件使用:通过简单的键盘+鼠标操作,快速完成搭配。1.基础快捷键1) Ctrl+V:复制选中对象第一步:鼠标左击物体,按下Ctrl+V 即可复制选中对象。2) Ctrl+G:组合多选对象第一步:按住Ctrl键多选对象--按住Ctrl+G--确定。3) Ctrl+B:解组选中对象第一步:左击选中对象...

Vue学习笔记之动态路由的参数传递应用及技巧

路由的参数传递:①通过params的类型· 配置路由格式:/router/:id· 传递的方式:在path后面跟上对应的值· 传递后形成的路径:/router/list,/router/profile这个就是前两篇中提到的"动态路由"中有应用过这个方法:②通过query的类型(对象方...