pom添加:
XML
<!-- websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
socket服务实现
java
import com.alibaba.fastjson.JSON;
import com.hdtd.safequalitycollect.common.utils.DateFormatterUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;
@Slf4j
@ServerEndpoint("/earlyWarning/{sid}")
@Component
public class EarlyWarningWebsocketServer {
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
*/
private static final CopyOnWriteArraySet<EarlyWarningWebsocketServer> webSocketSet = new CopyOnWriteArraySet<>();
/**
* 忽略预警消息列表
* key:用户id+时间戳,value:预警类型
*/
private static final HashMap<String,String> warningIgnoreList = new HashMap<>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 设置websocket超时时间
*/
public static final long MAX_TIME_OUT = 50L * 60L * 1000L;
/**
* 接收sid
*/
private String sid = "";
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
this.session = session;
session.setMaxIdleTimeout(MAX_TIME_OUT);
//如果存在就先删除一个,防止重复推送消息
for (EarlyWarningWebsocketServer webSocket : webSocketSet) {
if (webSocket.sid.equals(sid)) {
webSocketSet.remove(webSocket);
}
}
this.sid = sid;
webSocketSet.add(this);
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自" + sid + "的信息:" + message);
//群发消息
// String yyMmDdHh = DateFormatterUtils.getYyMmDdHh();
// if(ObjectUtils.isEmpty(warningIgnoreList.get(sid + yyMmDdHh))){
// // 清空warningIgnoreList中,key包含 sid 的,并且预警类型与message相同的记录
// Iterator<String> iterator = warningIgnoreList.keySet().iterator();
// while (iterator.hasNext()) {
// String key = iterator.next();
// if (key.contains(sid) && Objects.equals(warningIgnoreList.get(key), message)) {
// iterator.remove();
// }
// }
// warningIgnoreList.put(sid + yyMmDdHh, message);
// }
}
@OnError
public void onError(Session session, Throwable error) {
log.error(session.getId() + "发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
synchronized (session) {
this.session.getBasicRemote().sendText(message);
log.info("推送消息到" + sid + "成功,消息为:" + message);
}
}
/**
* 群发自定义消息
*/
public static void sendInfo(String message) {
for (EarlyWarningWebsocketServer productWebSocket : webSocketSet) {
try {
productWebSocket.sendMessage(message);
log.info("推送消息给全体用户" + "成功,消息为:" + message);
} catch (Exception e) {
log.error("推送消息失败:{}", e.getMessage());
}
}
}
/**
* 给指定连接用户自定义消息
*/
public static void sendInfo(SocketMsg socketMsg, @PathParam("sid") String sid) throws IOException {
String message = JSON.toJSONString(socketMsg);
log.info("推送消息到" + sid + ",推送内容:" + message);
for (EarlyWarningWebsocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if (sid == null || item.sid.equals(sid)) {
item.sendMessage(message);
}
} catch (IOException ignored) {
log.error("消息推送失败:{}", ignored.getMessage());
}
}
}
/**
* 给特定客户端发送信息
*/
public static void sendInfo(String message, String sid) throws IOException {
log.info("推送消息到" + sid + ",推送内容:" + message);
for (EarlyWarningWebsocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if (sid == null || item.sid.equals(sid)) {
item.sendMessage(message);
}
} catch (IOException ignored) {
log.error("消息推送失败:{}", ignored.getMessage());
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EarlyWarningWebsocketServer that = (EarlyWarningWebsocketServer) o;
return Objects.equals(session, that.session) &&
Objects.equals(sid, that.sid);
}
@Override
public int hashCode() {
return Objects.hash(session, sid);
}
}
项目启动后,socket服务自动启动
前端案例:
java
<!DOCTYPE HTML>
<html>
<head>
<title>WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://XXX:8080/earlyWarning/2");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
实现效果:
后台发送消息到前端,前端页面进行处理,前端也可以发送对应信息给后台,后台处理。
注意:socket连接时,需要前端提供对应的用户id,对用户进行区分,可以实现单个用户的发送接收。