首先项目需要导入相应的依赖
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
后端建立WebSocket类接受socket发送请求
@ServerEndpoint("/mySocket")
public class MySocket {
private static Map<String, Session> socketMap;
static {
socketMap = new HashMap<>();
}
@OnOpen
public void onOpen(Session session) {
socketMap.put("123", session);
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
JSONObject messageObj = JSON.parseObject(message);
Session receiverSession = socketMap.get(messageObj.get("receiverId"));
if (receiverSession != null) {
receiverSession.getBasicRemote().sendText("后端发送过来一条消息");
}
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println(throwable.getMessage());
}
@OnClose
public void onClose() {
socketMap.remove("123");
}
}
前端页面(mySocket.html)同样需要创建WebSocket与后端通信
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MySocket</title>
</head>
<script type="text/javascript" src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.js"></script>
<body>
<button onclick="sendMessage()">点击发送消息</button>
</body>
</html>
<script>
var websocket;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/test/mySocket");
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://localhost:8080/test/mySocket");
} else {
websocket = new SockJS("http://localhost:8080/test/mySocket");
}
websocket.onopen = function () {
console.log("连接建立");
}
websocket.onerror = function () {
console.log("连接出错");
};
websocket.onmessage = function (message) {
console.log("收到消息");
console.log(message);
}
websocket.onclose = function () {
console.log("连接关闭");
}
window.onbeforeunload = function () {
websocket.close();
}
function sendMessage() {
var message = {
receiverId: "123",
content: "发送一条消息"
};
websocket.send(JSON.stringify(message));
}
</script>
最后启动项目,访问项目的中的mySocket.html页面,如下
点击按钮