一、pom.xml配置
<!--spring boot 集成 websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二、WebSocketConfig Springboot引入配置
package com.sinosoft.gis.warning.webSocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpoint() {
return new ServerEndpointExporter();
}
}
三、WsServerEndpoint 配置接受链接和发送方法
package com.sinosoft.gis.warning.webSocket;
import com.alibaba.fastjson.JSON;
import com.sinosoft.gis.warning.disaster.domain.MeteorologicalWarning;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/warningWs/{id}")
@Component
public class WsServerEndpoint {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private static int onlineCount = 0;
private Session session;
public static CopyOnWriteArraySet<WsServerEndpoint> websocketServerSet = new CopyOnWriteArraySet<>();
private String id = "";
/**
* 连接成功
*
* @param session
*/
@OnOpen
public void onOpen(Session session, @PathParam("id") String id) {
log.info("onOpen >> 链接成功");
this.session = session;
//将当前websocket对象存入到Set集合中
websocketServerSet.add(this);
//在线人数+1
addOnlineCount();
log.info("有新窗口开始监听:" + id + ", 当前在线人数为:" + getOnlineCount());
this.id = id;
try {
//this.sendMessage("有新窗口开始监听:" + id + ", 当前在线人数为:" + getOnlineCount());
} catch (Exception e) {
log.error(e.toString());
}
}
/**
* 连接关闭
*
* @param session
*/
@OnClose
public void onClose(Session session) {
log.info("onClose >> 链接关闭");
//移除当前Websocket对象
websocketServerSet.remove(this);
//在内线人数-1
subOnLineCount();
log.info("链接关闭,当前在线人数:" + getOnlineCount());
}
/**
* 接收到消息
*
* @param message
* @param session
*/
@OnMessage
public void onMsg(String message, Session session) throws IOException {
log.info("接收到窗口:" + id + " 的信息:" + message);
//发送信息
for (WsServerEndpoint websocketServerEndpoint : websocketServerSet) {
try {
websocketServerEndpoint.sendMessage("接收到窗口:" + id + " 的信息:" + message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@OnError
public void onError(Session session, Throwable e) {
e.printStackTrace();
}
/**
* 群发自定义消息
*/
public void sendMessage(String message, HashSet<String> toSids) throws IOException {
log.info("推送消息到客户端 " + toSids + ",推送内容:" + message);
for (WsServerEndpoint item : websocketServerSet ) {
try {
if (toSids.size() <= 0) {
item.sendMessage(message);
} else if (toSids.contains(item.id)) {
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
/**
* 群发自定义消息
* MeteorologicalWarning 是自定义存信息的类
*/
public void sendMessage(ConcurrentHashMap<String, List<MeteorologicalWarning>> map) throws IOException {
for (String createBy : map.keySet() ) {
for (WsServerEndpoint item : websocketServerSet ) {
try {
if (createBy.equals(item.id)) {
String message = JSON.toJSONString(map.get(createBy));
log.info("推送消息到客户端:" + createBy + ",推送内容:" + message);
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
}
public static List<String> getWebSocketOnlineUsers(){
List<String> list = new ArrayList<>();
for (WsServerEndpoint item : websocketServerSet ) {
list.add(item.id);
}
return list;
}
/**
* 推送消息
*
* @param message
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
private void subOnLineCount() {
WsServerEndpoint.onlineCount--;
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
private void addOnlineCount() {
WsServerEndpoint.onlineCount++;
}
}
四、前端配置
function initWebSocketCreate() {
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
if (PAGE.islogin) {//执行需要登陆
if(!PAGE.isWebSocket){
websocket = new WebSocket("ws://localhost:8082/warningWs/" + user.id);
console.log("--组件初始化成功【webScoket】--");
PAGE.isWebSocket = true;
}else{
return;
}
}else{
console.log("当前用户未登录")
return;
}
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
console.log("预警通信正常");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
//setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
}
//将消息显示在网页上
function setMessageInnerHTML(data){
console.log(data);
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(message ){
websocket.send(message);
}