1.引入pom依赖
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-websocket</artifactId>
-
</dependency>
2.新建websocket的服务
WebSocketServer.java
-
/**
-
* @Author: wyb
-
* @Date: 2018/7/12 20:04
-
* @Description:websoceket具体业务实现
-
*/
-
@ServerEndpoint(value = "/websocket")
-
@Component
-
public class WebSocketServer {
-
private final Logger logger = LoggerFactory.getLogger(this.getClass());
-
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
-
private static int onlineCount = 0;
-
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
-
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
-
//与某个客户端的连接会话,需要通过它来给客户端发送数据
-
private Session session;
-
/**
-
* 连接建立成功调用的方法*/
-
@OnOpen
-
public void onOpen(Session session) {
-
this.session = session;
-
webSocketSet.add(this); //加入set中
-
addOnlineCount(); //在线数加1
-
}
-
/**
-
* 连接关闭调用的方法
-
*/
-
@OnClose
-
public void onClose() {
-
webSocketSet.remove(this); //从set中删除
-
subOnlineCount(); //在线数减1
-
}
-
/**
-
* 收到客户端消息后调用的方法
-
*
-
* @param message 客户端发送过来的消息*/
-
@OnMessage
-
public void onMessage(String message, Session session) {
-
System.out.println("来自客户端的心跳:" + message);
-
}
-
/**
-
* 发生错误时调用
-
@OnError
-
**/
-
public void onError(Session session, Throwable error) {
-
if(error != null)
-
logger.error("WebSocketServer onError:" + error.getMessage());
-
}
-
/***
-
* 对单一客户发送推送消息
-
* @param message 消息内容
-
*/
-
public void sendMessage(String message){
-
try{
-
this.session.getBasicRemote().sendText(message);
-
}catch (Exception ex){
-
logger.error("WebSocketServer sendMessage:" + ex.getMessage());
-
}
-
}
-
/**
-
* 群发自定义消息
-
* */
-
public static void broadcastSendInfo(String message){
-
try{
-
for (WebSocketServer item : webSocketSet) {
-
item.sendMessage(message);
-
}
-
}catch (Exception ex){
-
System.out.println(ex.getMessage());
-
}
-
}
-
public static synchronized void addOnlineCount() {
-
WebSocketServer.onlineCount++;
-
}
-
public static synchronized void subOnlineCount() {
-
WebSocketServer.onlineCount--;
-
}
-
}
3.向spring注入bean
-
@Bean
-
public ServerEndpointExporter serverEndpointExporter() {
-
return new ServerEndpointExporter();
-
}
4.添加websocket的js
MyWebSocket.js
-
/**
-
* Created by PC on 2018/2/11.
-
*/
-
var heartflag = true;
-
var webSocket = null;
-
var tryTime = 0;
-
$(function () {
-
initSocket();
-
});
-
/**
-
* 初始化websocket,建立连接
-
*/
-
function initSocket() {
-
if (!window.WebSocket) {
-
alert("您的浏览器不支持推送功能");
-
return false;
-
}
-
webSocket = null;
-
webSocket = new WebSocket("ws://" + window.location.host + "/websocket");
-
// 收到服务端消息
-
webSocket.onmessage = function (msg) {
-
if(msg.data == "&"){
-
// 暂时不用服务器反向发送心跳
-
}else{
-
popmsg(msg.data);
-
}
-
};
-
// 异常
-
webSocket.onerror = function (event) {
-
heartflag = false;
-
};
-
// 建立连接
-
webSocket.onopen = function (event) {
-
heartflag = true;
-
heart();
-
tryTime = 0;
-
};
-
// 断线重连
-
webSocket.onclose = function () {
-
heartflag = false;
-
tryTime++;
-
// 重试10次,每次之间间隔1秒
-
if (tryTime < 10) {
-
setTimeout(function () {
-
if(!heartflag){
-
webSocket = null;
-
initSocket();
-
//alert("第:" + tryTime + "次重新建链。");
-
}
-
}, 1000);
-
} else {
-
//alert("重连失败.");
-
}
-
};
-
heartflag = true;
-
}
-
// 连接成功后发送心跳
-
function heart() {
-
if (heartflag){
-
webSocket.send("&");
-
}
-
setTimeout("heart()", 10*1000);
-
}
-
function popmsg(popmsg){
-
//配置一个透明的询问框
-
layer.msg('', {
-
time: 20000, //20s后自动关闭
-
offset: 'rb',
-
content: '<div style="padding: 20px 100px;">'+ popmsg +'</div>'
-
});
-
}
这里显示使用了layer的部分内容
请注意最好建立心跳,因为如果不建立心跳那么网络中存在问题将有可能无法发现线路断链。