1.先是pom.xml添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.application.properties不需要添加任何配置 ,我只设置了一下服务server.port=8008
3.开启WebSocket支持
package com.pay.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启WebSocket支持
* @author zhengkai
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
4.然后是关键,WebSocket的各个监听方法:
package com.pay.websocket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pay.api.common.MyLog;
import com.pay.entity.PayOrders;
import com.pay.service.PayOrdersService;
import com.pay.utils.TimeMillisUtil;
import com.pay.web.ReceiptController;
@ServerEndpoint("/websocket/{token}")
@Component
public class WebSocketServer {
private final MyLog _log = MyLog.getLog(ReceiptController.class);
// 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
// concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
// 接收token
private String token = "";
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("token") String token) {
this.session = session;
webSocketSet.add(this); // 加入set中
addOnlineCount(); // 在线数加1
_log.info("有新窗口开始监听token:" + token + ",当前在线人数为" + getOnlineCount());
this.token = token;
try {
sendMessage("连接成功");
} catch (Exception e) {
_log.info("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
try {
webSocketSet.remove(this); // 从set中删除
subOnlineCount(); // 在线数减1
_log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
// @OnMessage
public void onMessage(String message, Session session) {
_log.info("收到来自窗口" + token + "的信息:" + message);
// 群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
//error.printStackTrace(); 打印异常日志
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
*/
@OnMessage
public void sendInfo(String message, @PathParam("token") String token) throws IOException {
//message前端发送过来的参数-可以自定义返回消息给前端
for (WebSocketServer item : webSocketSet) {
try {
// 这里可以设定只推送给这个sid的,为null则全部推送
if (token == null) {
item.sendMessage(message);
} else if (item.token.equals(token)) {
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
6.到这里,接下来用一个HTML5 页面,连接当前的WebSocket节点,接/发消息:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
<script>
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于
socket = new WebSocket("ws://localhost:8008/websocket/token");
//socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
socket.send("{'scope': '0','scopes': '5000','page': 0,'size': 5}");
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
</script>
</head>
<body>
</body>
</html>