使用Spring Boot + WebSocket + UniApp实现即时通讯

简介

本篇博客将详细介绍如何使用Spring Boot、WebSocket和UniApp技术栈来实现一个跨平台的即时通讯聊天应用。我们将分为前端和后端两部分进行讲解,并提供详细的代码示例。

前端:UniApp

1. 创建UniApp项目

首先,我们需要使用HBuilderX创建一个UniApp项目。选择“Hello uni-app”模板作为基础结构。

2. 用户界面设计

在pages/index目录下,我们创建一个名为chat的页面,用于展示聊天界面。

<!-- pages/index/chat.vue -->
<template>
  <view class="container">
    <scroll-view class="messages" :style="{height: 'calc(100% - 60px)'}">
      <view v-for="(msg, index) in messages" :key="index" :class="msg.type">
        {{ msg.content }}
      </view>
    </scroll-view>
    <input v-model="inputMessage" @input="onInput" placeholder="输入消息..." />
    <button @click="sendMessage">发送</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      messages: [],
      inputMessage: '',
    };
  },
  methods: {
    onInput() { /* ... */ },
    sendMessage() {
      const message = this.inputMessage;
      this.socket.send(JSON.stringify({ type: 'message', content: message }));
      this.inputMessage = '';
    },
    onSocketOpen() { /* ... */ },
    onSocketMessage(event) { /* ... */ },
    onSocketClose(event) { /* ... */ },
    onSocketError(event) { /* ... */ },
  },
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.messages {
  flex: 1;
  overflow-y: scroll;
}
</style>

3. 集成WebSocket客户端

在main.js中,我们初始化WebSocket客户端并与后端进行通信。

// main.js
import socket from './utils/socket';
Vue.prototype.$socket = socket;

// utils/socket.js
import io from 'socket.io-client';
const socket = io('http://localhost:8080');
export default socket;

后端:Spring Boot + WebSocket

1. 创建Spring Boot项目

使用Spring Initializr创建一个新项目,并添加spring-boot-starter-websocket依赖。

<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2. WebSocket配置

配置WebSocketConfig以启用WebSocket并定义端点。

// WebSocketConfig.java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketEndpoints(WebSocketEndpointRegistry registry) {
        registry.addEndpoint("/chat").withSockJS();
    }

}

3. 消息处理器

定义ChatHandler来处理WebSocket事件。

// ChatHandler.java
@ServerEndpoint("/chat")
public class ChatHandler {

    private static Set<Session> onlineUsers = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        onlineUsers.add(session); // 用户上线时添加到在线列表
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 广播消息给所有在线用户
        for (Session userSession : onlineUsers) {
            userSession.getBasicRemote().sendText(message);
        }
    }

    @OnClose
    public void onClose(Session session) {
        onlineUsers.remove(session); // 用户下线时从在线列表移除
    }

    @OnError
    public void onError(Session session, Throwable error) { /* ... */ }
}

4. 消息广播逻辑

实现消息发送和接收的逻辑。

// MessageService.java
@Service
public class MessageService {

    private static Set<Session> onlineUsers = new ConcurrentHashMap<>();

    public void broadcastMessage(String message) {
        for (Session session : onlineUsers) {
            session.getBasicRemote().sendText(message);
        }
    }

    // 其他必要的方法...
}
  • 13
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

10年程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值