websocket
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @Description: 开启WebSocket支持
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
import com.alibaba.fastjson.JSONObject;
import com.yishu.education.service.BlockService;
import com.yishu.education.service.OrderService;
import com.yishu.education.service.TransactionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
@ServerEndpoint(value = "/ws/asset")
@Component
public class WebSocketServer {
@PostConstruct
public void init() {
System.out.println("websocket 加载");
}
private static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
static BlockService blockService;
static OrderService orderService;
static TransactionService transactionService;
@Autowired
public void setBlockService(BlockService blockService) {
WebSocketServer.blockService = blockService;
}
@Autowired
public void setOrderService(OrderService orderService) {
WebSocketServer.orderService = orderService;
}
@Autowired
public void setTransactionService(TransactionService transactionService) {
WebSocketServer.transactionService = transactionService;
}
private static final AtomicInteger OnlineCount = new AtomicInteger(0);
// concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
SessionSet.add(session);
int cnt = OnlineCount.incrementAndGet(); // 在线数加1
logger.info("有连接加入,当前连接数为:{}", cnt);
Map<String, String> map = new HashMap<>();
String blocks = blockService.selectNextBlock();
String orders = orderService.selectNewOrderAndTransaction();
String transactions = transactionService.selectTransactionAvgOfToday(null, null);
map.put("blocks", blocks);
map.put("orders", orders);
map.put("transactions", transactions);
String data = JSONObject.toJSONString(map);
// logger.info("onOpen-------------" + data);
SendMessage(session, data);
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
SessionSet.remove(session);
int cnt = OnlineCount.decrementAndGet();
logger.info("有连接关闭,当前连接数为:{}", cnt);
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
logger.info("来自客户端的消息:{}", message);
try {
Map<String, String> map = new HashMap<>();
String blocks = blockService.selectNextBlock();
String orders = orderService.selectNewOrderAndTransaction();
String transactions = transactionService.selectTransactionAvgOfToday(null, null);
map.put("blocks", blocks);
map.put("orders", orders);
map.put("transactions", transactions);
String data = JSONObject.toJSONString(map);
// logger.info("onMessage-------------" + data);
SendMessage(session, data);
System.out.println(data);
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 出现错误
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
logger.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId());
error.printStackTrace();
}
/**
* 发送消息,实践表明,每次浏览器刷新,session会发生变化。
*
* @param session
* @param message
*/
public static void SendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(String.format(message, session.getId()));
} catch (IOException e) {
logger.error("发送消息出错:{}", e.getMessage());
e.printStackTrace();
}
}
public static void SendMessage(Session session, Map<String, List> map) {
try {
if (session.isOpen()) {
session.getBasicRemote().sendObject(map);
}
} catch (IOException e) {
logger.error("发送消息出错:{}", e.getMessage());
e.printStackTrace();
} catch (EncodeException e) {
e.printStackTrace();
}
}
/**
* 群发消息
*
* @param message
* @throws IOException
*/
public void BroadCastInfo(String message) throws IOException {
for (Session session : SessionSet) {
if (session.isOpen()) {
SendMessage(session, message);
}
}
}
/**
* 指定Session发送消息
*
* @param sessionId
* @param message
* @throws IOException
*/
public static void SendMessage(String message, String sessionId) throws IOException {
Session session = null;
for (Session s : SessionSet) {
if (s.getId().equals(sessionId)) {
session = s;
break;
}
}
if (session != null) {
SendMessage(session, message);
}
}
}
备注:放到服务器外网,websocket端口(和程序端口一样)也要映射