主要是再小程序有个地方需要获取实时的订单 所以写样这么一部分 websocket操作其实很简单
pom依赖
org.springframework.boot spring-boot-starter-websocket com.alibaba fastjson 1.2.58
WebSocketConfig.java
package com.ruoyi.project.tool.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 {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketServer.java
package com.ruoyi.project.tool.websocket;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
@ServerEndpoint("/db/imserver/{userId}")
@Component
@Log4j2
public class WebSocketServer {
// static Log log=LogFactory.get(WebSocketServer.class);
private static int onlineCount = 0;
private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();
private Session session;
private String userId = "";
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
log.info("userId:"+userId);
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
log.info("创建用户1");
webSocketMap.put(userId, this);
// 加入set中
} else {
log.info("创建用户2");
webSocketMap.put(userId, this);
// 加入set中
addOnlineCount();
// 在线数加1
}
log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
try {
Map
uniapp前端
websockets(){
//连接
uni.connectSocket({
url:'ws://127.0.0.1:8010/db/imserver/1'
})
//打开websocket回调
uni.onSocketOpen(function (res) {
console.log('WebSocket连接已打开!');
});
//连接失败回调
uni.onSocketError(function (res) {
console.log('WebSocket连接打开失败,请检查!');
uni.showToast({
title:'WebSocket连接打开失败,请检查!',
icon:'none'
})
});
//服务端过来内容之后打印
uni.onSocketMessage(function (res) {
console.log('收到服务器内容:' + res.data);
console.log('收到服务器内容:' + JSON.parse(res.data).msg);
});
//关闭websocket打印
uni.onSocketClose(function (res) {
console.log('WebSocket 已关闭!');
uni.showToast({
title:'WebSocket 已关闭!',
icon:'none'
})
});
}



