功能舉例: 通過特定操作實時推送到頁面反饋進行彈窗和播放音樂。
先貼源代碼地址: 點我GO
- 引入pom
創建一個基礎的Spring Boot工程(沒有特定版本),並在pom.xml
中引入需要的依賴內容:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- 配置配置文件(看需要配置) :
spring.freemarker.template-loader-path=classpath:/templates
spring.mvc.static-path-pattern=/static/**
- 在需要接收消息的頁面進行配置 :
<script>
var websocket =null;
if('WebSocket' in window){
//這裏的地址根據第五步配置的註解地址填寫
websocket = new WebSocket('ws://127.0.0.1:8080/webSocket');
}else {
alert('您的瀏覽器不支持websocket。');
}
websocket.onopen = function (event) {
console.log('建立連接');
}
websocket.onclose = function (event) {
console.log('連接關閉');
}
websocket.onmessage = function (event) {
console.log('收到消息:'+event.data)
}
websocket.onerror = function () {
alert('websocket通信發生錯誤');
}
websocket.onbeforeunload = function(){
websocket.close();
}
</script>
- 配置WebSocket Bean :
@Component
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointConfigurator(){
return new ServerEndpointExporter();
}
}
- 實現webSocket
@Component
@ServerEndpoint("/webSocket")
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this);
System.out.println("新的連接 總數:"+webSocketSet.size());
}
@OnClose
public void onColse(){
webSocketSet.remove(this);
System.out.println("斷開連接 總數:"+webSocketSet.size());
}
@OnMessage
public void onMessage(String message){
System.out.println("收到客戶端發來的消息:"+message);
}
public void sendMessage(String message){
for (WebSocket webSocket : webSocketSet){
System.out.println("廣播消息:"+message);
try {
webSocket.session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 配置觸發控制器
@RequestMapping("/shop")
public class ListController {
@Autowired
private WebSocket webSocket;
/**
* 接收推送來的消息的頁面
* @return
*/
@RequestMapping(value ="/list")
public String list(){
return "list";
}
/**
* 觸發推送
* 舉例:list方法可以是訂單列表,這個方法可以是下單的接口,下單後,list的訂單列表提示收到新訂單。
* @return
*/
@RequestMapping(value = "/test")
@ResponseBody
public String test(){
webSocket.sendMessage("hello,來了新數據呢~");
return "send over,Please return to the list request page。";
}
}
- 配置websocket響應提示:
<audio id="notice" loop="loop">
<source src="http://fs.w.kugou.com/201905211603/af65d55785b7e97732644d0900fdf8b9/G146/M04/17/18/MocBAFx43JWAdxDBAC92YHGZWaY748.mp3" type="audio/mpeg">
</audio>
websocket.onmessage = function (event) {
console.log('收到消息:'+event.data)
alert(event.data);
var myAuto = document.getElementById('notice');
console.log('開始播放音樂!15秒後停止...');
myAuto.play();
setTimeout(function () {
myAuto.pause();
console.log('音樂停止...')
},15000)
}
- 測試展示:
請求list地址 http://localhost:8080/shop/list
後臺輸出:
觸發請求條件: http://localhost:8080/shop/test
list頁面接收到消息:
查看:
如有不當之處,請予指正! 如果你有什麼疑問也歡迎隨時聯繫我共同探討。
Email:wdnnccey#gmail.com
你配不上自己的野心 也辜負了所受的苦難