1、WebSocketConfig 配置类
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 serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2、WebSocket 消息发送接收
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
@ServerEndpoint(value = "/web/{id}")
public class WebSocketProcess {
private static ConcurrentHashMap<Long, WebSocketProcess> concurrentHashMap = new ConcurrentHashMap<>(16);
private Session session;
@OnOpen
public void onOpen(Session session, @PathParam("id") long id) {
this.session = session;
concurrentHashMap.put(id, this);
log.info("Open a websocket. id={}", id);
}
@OnClose
public void onClose(Session session, @PathParam("id") long id) {
concurrentHashMap.remove(id);
log.info("close a websocket, concurrentHashMap remove sessionId= {}", id);
}
@OnMessage
public void onMessage(String message, @PathParam("id") String id) {
log.info("receive a message from client id={},msg={}", id, message);
}
@OnError
public void onError(Session session, Throwable error) {
log.error("Error while websocket.", error);
}
public void sendMessage(long id, String message) throws Exception {
WebSocketProcess webSocketProcess = concurrentHashMap.get(id);
if (!ObjectUtils.isEmpty(webSocketProcess)) {
if (webSocketProcess.session.isOpen()) {
webSocketProcess.session.getBasicRemote().sendText(message);
} else {
log.error("websocket session={} is closed ", id);
}
} else {
log.error("websocket session={} is not exit ", id);
}
}
public void sendAllMessage(String msg) throws Exception {
log.info("online client count={}", concurrentHashMap.size());
Set<Map.Entry<Long, WebSocketProcess>> entries = concurrentHashMap.entrySet();
for (Map.Entry<Long, WebSocketProcess> entry : entries) {
Long cid = entry.getKey();
WebSocketProcess webSocketProcess = entry.getValue();
boolean sessionOpen = webSocketProcess.session.isOpen();
if (sessionOpen) {
webSocketProcess.session.getBasicRemote().sendText(msg);
} else {
log.info("cid={} is closed,ignore send text", cid);
}
}
}
}
3、消息推送 Controller
import com.xyl.web.controller.common.WebSocketProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/testws")
public class WebSocketController {
@Autowired
private WebSocketProcess webSocketProcess;
@PostMapping(value = "sendMsgToClientById")
public void sendMsgToClientById(@RequestParam long id, @RequestParam String text) {
try {
webSocketProcess.sendMessage(id, text);
} catch (Exception e) {
e.printStackTrace();
}
}
@PostMapping(value = "sendMsgToAllClient")
public void sendMsgToAllClient(@RequestParam String text) {
try {
webSocketProcess.sendAllMessage(text);
} catch (Exception e) {
e.printStackTrace();
}
}
@Scheduled(cron = "0/5 * * * * ?")
private void configureTasks() throws Exception {
webSocketProcess.sendAllMessage("向前端推送消息内容");
}
}
4、测试 HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>websocket 测试</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="content"></div>
</body>
<script type="text/javascript">
$(function(){
var ws;
if("WebSocket"in window){
$("#content").html("您的浏览器支持 webSocket!");
let clientID = Math.ceil(Math.random()*100);
ws = new WebSocket("ws://127.0.0.1:9095/web/"+clientID);
ws.onopen=function(){
$("#content").append("<p>与服务端建立连接建立成功!您的客户端 ID="+clientID+"</p>");
ws.send("你好服务端!我是客户端 "+clientID);
}
ws.onmessage=function(evt){
let received_msg = evt.data;
$("#content").append("<p>接收到服务端消息:"+received_msg+"</p>");
};
ws.onclose=function(){
console.error("连接已经关闭.....");
};
}else{
$("#content").html("您的浏览器不支持 webSocket!");
}
})
</script>
</html>