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

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>

三、运行步骤

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

Linux发行版需要杀软吗?卡巴斯基推出免费KVRT病毒扫描清理工具

IT之家 6 月 4 日消息,你认为使用 Linux 发行版,需要杀毒软件吗?或许很多用户认为 Linux 发行版偏小众,因此受到黑客攻击的风险也相对较小,不过卡巴斯基并不这么认为,近期推出了适用于 Linux 平台的杀毒软件。最新上线的 Linux 版本 Kaspersky Virus Remov...

红帽最新的企业 Linux 发行版具有解决混合云复杂性的新功能

据zdnet网5月1日报道,红帽这家 Linux 和超云领导者今天发布了其最新的旗舰 Linux 发行版 Red Hat Enterprise Linux (RHEL) 9.4,此前上周宣布对已有十年历史的流行 RHEL 7.9 再支持四年。这个领先的企业 Linux 发行版的最新版本引入了许多新功...

带你五步学会Vue SSR

作者:liuxuan 前端名狮转发链接:https://mp.weixin.qq.com/s/6K6GUHcLwLG4mzfaYtVMBQ前言SSR大家肯定都不陌生,通过服务端渲染,可以优化SEO抓取,提升首页加载速度等,我在学习SSR的时候,看过很多文章,有些对我有很大的启发作用,有些就只是照搬官...

Git 分支管理策略汇总

最近,团队新入职了一些小伙伴,在开发过程中,他们问我 Git 分支是如何管理的,以及应该怎么提交代码?我大概说了一些规则,但仔细想来,好像也并没有形成一个清晰规范的流程。所以查了一些资料,总结出下面这篇文章,一共包含四种常见的分支管理策略,分享给大家。Git flow在这种模式下,主要维护了两类分支...

高效使用 Vim 编辑器的 10 个技巧

在 Reverb,我们使用 MacVim 来标准化开发环境,使配对更容易,并提高效率。当我开始使用 Reverb 时,我以前从未使用过 Vim。我花了几个星期才开始感到舒服,但如果没有这样的提示,可能需要几个月的时间。这里有十个技巧可以帮助你在学习使用 Vim 时提高效率。1. 通过提高按键重复率来...

美国民众负债累累 但今年假期消费者支出仍将创下新高

智通财经APP获悉,在迎接假期之际,许多美国人已经背负了创纪录的信用卡债务。然而,今年假期消费者支出仍将创下新高。根据美国零售联合会(NRF)上周发布的报告,预计今年11月1日至12月31日期间的消费总额将达到创纪录的9795亿至9890亿美元之间。NRF首席经济学家Jack Kleinhenz表示...