配置
package com.mlfo.wmb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WekSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
实现
package com.mlfo.wmb.message.websocket;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.mlfo.wmb.message.controller.Command;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@Slf4j
@CrossOrigin(origins = "*")
@ServerEndpoint("/websocket/{userId}")
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
private static Map<String, Session> sessionPool = new HashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam(value = "userId") String userId) {
try {
this.session = session;
webSockets.add(this);
sessionPool.put(userId, session);
log.info("【websocket消息】有新的连接,总数为:" + webSockets.size());
} catch (Exception e) {
}
}
@OnClose
public void onClose() {
try {
webSockets.remove(this);
log.info("【websocket消息】连接断开,总数为:" + webSockets.size());
} catch (Exception e) {
}
}
@OnMessage
public void onMessage(String cmd) {
//todo 现在有个定时任务刷,应该去掉
log.info("【websocket消息】收到客户端消息:" + cmd);
if(cmd.equals("random")){
testGetList();
}
}
public void testGetList(){
String cmd = "random";
JSONObject ob = new JSONObject();
ob.put("uuid",IdUtil.simpleUUID());
Command command = new Command(cmd, ob);
Session session = sessionPool.get("1");
if (session != null && session.isOpen()) {
try {
log.info("【websocket消息】 发送数据:" + command.toString());
session.getAsyncRemote().sendText(JSONObject.toJSONString(command));
} catch (Exception e) {
e.printStackTrace();
}
} else {
log.info("【websocket消息】 未成功发送消息");
}
}
// 此为广播消息
public void sendAllMessage(String message) {
log.info("【websocket消息】广播消息:" + message);
for (WebSocket webSocket : webSockets) {
try {
if (webSocket.session.isOpen()) {
webSocket.session.getAsyncRemote().sendText(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 此为单点消息
public void sendOneMessage(String userId, String message) {
Session session = sessionPool.get(userId);
if (session != null && session.isOpen()) {
try {
log.info("【websocket消息】 单点消息:" + message);
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 此为单点消息(多人)
public void sendMoreMessage(String[] userIds, String message) {
for (String userId : userIds) {
Session session = sessionPool.get(userId);
if (session != null && session.isOpen()) {
try {
log.info("【websocket消息】 单点消息:" + message);
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Scheduled(cron = "0/1 * * * * ?")
public void sendMessage() {
// JSONObject obj = new JSONObject();
// obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_CHECK);//业务类型
// obj.put(WebsocketConst.MSG_TXT, "心跳响应");//消息内容
// session.getAsyncRemote().sendText(obj.toJSONString());
// log.info("10秒定时发送消息....");
Session session = sessionPool.get("1");
//log.info("session:" + session);
JSONObject jsonObject = new JSONObject();
jsonObject.put("cmd","time");
String now = DateUtil.now();
jsonObject.put("dateTime",now);
Command command = new Command("time", DateUtil.now());
if (session != null && session.isOpen()) {
try {
//log.info("【websocket消息】 定时发送时间消息:" + command.toString());
session.getAsyncRemote().sendText(JSONObject.toJSONString(command));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
版权声明:本文为weixin_39059447原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。