uniapp + ruoyi 完成websocket即时通讯

视频版:uniapp + ruoyi 完成websocket即时通讯_哔哩哔哩_bilibili

1、pom.xml中添加

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

2、创建如下包和类

package com.ruoyi.framework.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    /**
     * 注入一个ServerEndpointExporter,该bean会自动舌侧使用 @ServerEndpoint注解声明websocket endpoind
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
package com.ruoyi.framework.websocket;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created with IntelliJ IDEA.
 * @ Description:
 * @ ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@Component
@Service
@ServerEndpoint(value = "/imserver/{sid}")
public class WebSocketServer {

    static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    //当前在线连接数
    private static int onlineCount = 0;
    //存放每个客户端对应的MyWebSocket对象
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    private Session session;

    //接收sid
    private String sid = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        this.sid = sid;
        addOnlineCount();           //在线数加1
        try {
            sendMessage("conn_success");
            log.info("有新窗口开始监听:" + sid + ",当前在线人数为:" + getOnlineCount());
        } catch (IOException e) {
            log.error("websocket IO Exception");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1

        log.info("释放的sid为:"+sid);

        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());

    }

    /**
     * 收到客户端消息后调用的方法
     * @ Param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口" + sid + "的信息:" + message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("fromUser",sid);
                jsonObject.put("msg",message);
                item.sendMessage(jsonObject.toJSONString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @ Param session
     * @ Param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
        log.info("推送消息到窗口" + sid + ",推送内容:" + message);

        for (WebSocketServer item : webSocketSet) {
            try {
                //为null则全部推送
                if (sid == null) {
//                    item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }
}

3、SecurityConfig中配置拦截过滤

 

 增加 .antMatchers("/imserver/**").anonymous()

 4、hbuilderx 中创建uniapp项目

5、 index.vue

<template>
	<view>
		<view>
			<view class="title" v-for="(item,index) in msgList" :key="index"
				:style="item.fromUser == loginUserId ?'text-align: right;':'text-align: left;'">
				用户{{item.fromUser}}说:{{item.msg}}
			</view>
		</view>

		<input v-model="content" placeholder="请输入内容" />
		<button @click="send">发送</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello',
				socketOpen: false,
				socketMsgQueue: [],
				loginUserId: '', //当前登录的用户id
				content: '', //发送的内容
				msgList: []
			}
		},
		onLoad(option) {
			let that = this
			this.loginUserId = option.id
			//页面加载后,建立websocket连接
			uni.connectSocket({
				url: 'ws://localhost:8888/imserver/' + this.loginUserId
			});

			uni.onSocketOpen(function(res) {
				that.socketOpen = true;
				for (var i = 0; i < that.socketMsgQueue.length; i++) {
					that.sendSocketMessage(that.socketMsgQueue[i]);
				}
				that.socketMsgQueue = [];
			});

			uni.onSocketMessage(function(res) {
				console.log('收到服务器内容:' + res.data);
				if (res.data != 'conn_success') {
					that.msgList.push(JSON.parse(res.data))
				}

			});

		},
		methods: {
			send() {
				this.sendSocketMessage(this.content)
				this.content = ''
			},
			sendSocketMessage(msg) {
				if (this.socketOpen) {
					uni.sendSocketMessage({
						data: msg
					});
				} else {
					this.socketMsgQueue.push(msg);
				}
			}
		}
	}
</script>

<style>
	.title {
		text-align: left;
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>

6、最终效果

用户1界面:

 用户2界面

  • 8
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

cesium vue

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

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

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

打赏作者

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

抵扣说明:

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

余额充值