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界面
|