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

SpringBoot+Netty+Vue实现在线聊天

ruisui882个月前 (04-22)技术分析26

以下是使用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实现在线聊天” 的相关文章

Python 幕后:Python导入import的工作原理

更多互联网精彩资讯、工作效率提升关注【飞鱼在浪屿】(日更新)Python 最容易被误解的方面其中之一是import。Python 导入系统不仅看起来很复杂。因此,即使文档非常好,它也不能让您全面了解正在发生的事情。唯一方法是研究 Python 执行 import 语句时幕后发生的事情。注意:在这篇文...

el-table内容\n换行解决办法

问题请求到的数据带有换行符 '\n'但页面展示时不换行statusRemark: "\"1、按期完成计划且准确率100%,得100分;\n2、各项目每延误1天,扣1分;每失误1次或者员工投诉1次,扣3分,失误层面达到公司级影响较大的,该项绩效分数为0\"\n&...

2024年,不断突破的一年

迈凯伦F1车队不久前拿下了2024年度总冠军,距离上一次还是二十几年前。在此期间,另一领域内,一个充满革新活力的腕表品牌——RICHARD MILLE理查米尔,正不断发展,与F1运动、帆船、古董车展等领域,共享着对速度与极限的无尽向往。RICHARD MILLE的发展与F1车手们在赛道上的卓越表现交...

JavaScript数组操作:掌握常用方法,提升开发效率

JavaScript数组操作:从增删改查到高级应用本文深入解析JavaScript中常用的数组方法,包括push、unshift、pop、shift、map、filter、reverse、at 和 slice。通过详细的例子和应用场景,帮助开发者快速掌握这些方法,提升代码效率和可读性。开篇点题作为J...

在vue项目中封装WebSockets请求

在Vue项目中封装WebSocket请求包括以下步骤:1. 安装WebSocket库:首先,导入WebSocket库,例如`vue-native-websocket`或`socket.io-client`。根据项目需求选择适当的库,并根据官方文档进行安装和配置。2. 创建WebSocket服务:在V...

推荐一个Java微服务商业级Sass开源电商小程序(开源,企业级项目)

使用Java微服务开发,SpringBoot2框架、MyBatis-plus持久层框架、Redis作为缓存、MySql8作为数据库。 前端vuejs作为开发语言,使用uniapp编码,同时支持微信小程序、安卓App、苹果App。 支持集群部署,单机部署。 unimall 针对中小商户、企业和个人消...