springBoot2.0整合webSocket 服务器主动推送数据到前端,并且弹框提示带有音乐提醒

1、建立一个maven项目(我这里使用的是eclipse创建的 maven项目)

File——>new——>other——>maven

2、修改jdk版本,必须为1.8

3、整个项目目录如下

4、pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.han</groupId>
	<artifactId>SpringBoot-WebSocket</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBoot-WebSocket Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.5.RELEASE</version>
		<relativePath />
	</parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<!-- json工具 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>LATEST</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!--html-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringBoot-WebSocket</finalName>
	</build>
</project>

WebSocketServer服务器端实现

package com.han.websocket;

import java.io.IOException;
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.ServerEndpoint;

import org.springframework.stereotype.Component;

/**
 * WebSocketServer服务器端
 * 
 * @author han
 *
 */
@Component
@ServerEndpoint("/WebSocketServer")
public class WebSocketServer {
	// 静态变量,用来记录当前在线连接数,应该把它设计成线程安全的
	private static int onlineCount = 0;
	// concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象,若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
	private static CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<WebSocketServer>();
	private Session session;

	@OnOpen
	public void onOpen(Session session) {
		this.session = session;
		webSockets.add(this);
		addOnlineCount(); // 在线数加1
		System.out.println("【websocket消息】有新的连接,当前总数为:" + webSockets.size());
	}

	@OnClose
	public void onClose() {
		webSockets.remove(this);
		subOnlineCount(); // 在线数减1
		System.out.println("【websocket消息】连接断开,当前总数为:" + webSockets.size());
	}

	@OnMessage
	public void onMessage(String message) {
		System.out.println("【websocket消息】收到消息:" + message);
	}

	/**
	 * 
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println("【websocket发生错误】:" + error);
		error.printStackTrace();
	}

	/**
	 * 服务器主动推送消息
	 */
	public void sendMessage(String message) {
		try {
			for (WebSocketServer webSocket : webSockets) {
				System.out.println("【websocket消息】发送消息:" + message);
				webSocket.session.getBasicRemote().sendText(message);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static synchronized int getOnlineCount() {
		return onlineCount;
	}

	public static synchronized void addOnlineCount() {
		WebSocketServer.onlineCount++;
	}

	public static synchronized void subOnlineCount() {
		WebSocketServer.onlineCount--;
	}
}

WebSocketConfig配置断点

package com.han.config;

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.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * webSocket配置类,绑定前端连接端点url及其他信息
 * 
 * @author han
 *
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

	@Bean
	public ServerEndpointExporter serverEndpointExporter() {
		return new ServerEndpointExporter();
	}

	/**
	 * 注册webSocket端点
	 */
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		// 添加一个/WebSocketServer端点,客户端就可以通过这个端点来进行连接;withSockJS作用是添加SockJS支持
		registry.addEndpoint("/WebSocketServer").setAllowedOrigins("*").withSockJS();
	}
}

WebSocketController控制器

package com.han.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.han.util.Result;
import com.han.websocket.WebSocketServer;

/**
 * webSocket访问控制器
 * 
 * @author han
 *
 */
@Controller
public class WebSocketController {
	@Autowired
	private WebSocketServer webSocketServer;

	@RequestMapping("/index")
	public String index(String mesaage) {
		return "/index";
	}

	/**
	 * 发送消息页面
	 * 
	 * @param mesaage
	 * @return
	 */
	@RequestMapping("/webSocket/senMessage")
	public ModelAndView senMessage(String mesaage) {
		ModelAndView mav = new ModelAndView("/sendMessage");
		return mav;
	}

	/**
	 * 接收消息页面
	 * 
	 * @param mesaage
	 * @return
	 */
	@RequestMapping("/webSocket/receiveMessage")
	public ModelAndView receiveMessage(String mesaage) {
		ModelAndView mav = new ModelAndView("/receiveMessage");

		return mav;
	}

	/**
	 * 服务器端推送消息
	 * 
	 * @return
	 */
	@RequestMapping("/serverSendMessage")
	@ResponseBody
	public Result sendMessage(String message) {
		Result result = new Result();
		try {
			result.setCode("1000");
			result.setMsg("发送消息成功");
			webSocketServer.sendMessage(message);
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode("1001");
			result.setMsg("发送消息失败");
			result.setData(null);
		}
		return result;
	}
}

发送消息页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>发送消息页面</title>
</head>
<body>
<form id="sendMessage">
   <input type="text" id="msg" name="message" >
   <input type="button" id="btn" value="发送消息">
</form>
</body>
<script type="text/javascript" src="/static/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/static/js/layer-v3.1.1/layer/layer.js"></script>
<script type="text/javascript">
$(function(){
	$("#btn").on("click",function(){
	    var param = $("#sendMessage").serialize();
		$.ajax({
            url: "/serverSendMessage",
            type:"POST",
            data:param, 
            success: function(data){
           	 if(data.code==1000){
               	 layer.msg('发送消息成功',{icon:1,time:1000});
                }else if(data.code==1001){
              	     layer.msg('发送失败',{icon:2,time:1000});
                }
            }
        });
	});
}) 

</script>
</html>

接收消息页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>接收消息页面</title>
</head>
<body>
<audio src="/static/music/msg.mp3" id="myaudio" controls="controls" loop="false" hidden="true">
</body>
<script type="text/javascript" src="/static/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/static/js/layer-v3.1.1/layer/layer.js"></script>
<script type="text/javascript">
var websocket=null;
if('WebSocket' in  window){
	websocket=new WebSocket('ws://10.2.91.25:8010/WebSocketServer');
}else{
	 layer.msg('该浏览器不支持websocket',{icon:2,time:1000});
}
websocket.onopen=function(event){
	console.info('建立连接');
}
websocket.onclose=function(event){
	console.info('关闭连接');
}
websocket.onmessage=function(event){
	if(event.data!=null){
		document.getElementById('myaudio').play();
		layer.confirm("您有新的消息请注意查收!", {
		  btn: ['确定','取消']
		}, function(){
			closePlay();
			window.location.href="/receiveMessage";//跳转至未处理消息页面
		},function(){
			closePlay();
		});
	}
	console.info('收到消息'+event.data);
	//弹框提醒,播放音乐
}
websocket.onerror=function(){
	console.info('websocket通讯发生错误!');
}
websocket.onbeforeunload=function(){
	websocket.close();
}
//发送消息
function send() {
    var message = $("#msg").val();
    websocket.send(message);
}
function autoPlay() {
    var myAuto = document.getElementById('myaudio');
    myAuto.play();
}
function closePlay() {
    var myAuto = document.getElementById('myaudio');
    myAuto.pause();
    myAuto.load();
}
</script>
</html>

效果图如下(发送完消息,接收消息页面弹框提示并且带有音乐):


这里提示一下使用谷歌浏览器测试页面会报receiveMessage:27 Uncaught (in promise) DOMException:

具体解决方案如下

H5视频、音频不能自动播放,Uncaught (in promise) DOMException: play() failed because the user didn't

错误原因:Chrome的autoplay政策在2018年4月做了更改。

解决办法:

第一步,在chrome浏览器中输入:chrome://flags/#autoplay-policy

第二步,在Autoplay policy中将Default改为No user gesture is required

第三步,点击下方的“RELAUNCH NOW”,就大功告成了!

 

参考链接:

HTML <video> 标签 http://www.runoob.com/tags/tag-video.html

源码下载链接:https://download.csdn.net/download/semial/10930628

 

 

 

### 回答1: Spring Boot 2.0 是一套快速开发框架,其中包含了 WebSocket 模块,能够轻松地集成 WebSocket,实现服务端主动前端推送数据。 首先,在pom.xml文件中引入Spring Boot的Starter Websocket依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> 然后,在Spring Boot的启动类上使用@EnableWebSocket注解开启 WebSocket: @SpringBootApplication @EnableWebSocket public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } 接着,编写一个 WebSocketEndpoint 类用于处理 WebSocket 连接和消息的收发: @Component public class WebSocketEndpoint implements WebSocketHandler { private static final List<WebSocketSession> SESSIONS = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { SESSIONS.add(session); } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { // 接收到消息 } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { SESSIONS.remove(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { SESSIONS.remove(session); } @Override public boolean supportsPartialMessages() { return false; } // 服务器前端推送消息 public static void sendMessage(String message) throws IOException { for (WebSocketSession session : SESSIONS) { if (session.isOpen()) { session.sendMessage(new TextMessage(message)); } } } } 最后,当服务端需要向前端推送数据时,可以调用 WebSocketEndpoint 中的 sendMessage 方法: WebSocketEndpoint.sendMessage("Hello, websocket!"); 前端则需要开启 WebSocket 连接,并在 onmessage 方法中接收服务端推送数据: var socket = new WebSocket("ws://localhost:8080/websocket"); socket.onmessage = function(event) { var data = event.data; // 处理服务端推送数据 }; 总之,Spring Boot 2.0 整合 WebSocket 实现服务端主动前端推送数据非常简单,只需要几行代码即可实现。 ### 回答2: Spring Boot 2.0 提供了与 WebSocket 相关的依赖和注解,可以方便地实现与前端的实时通信。下面介绍如何使用 Spring Boot 2.0 整合 WebSocket 实现服务器主动推送数据前端。 首先,在 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 然后,创建一个 WebSocket 配置类,使用 `@EnableWebSocket` 注解启用 WebSocket: ``` @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myWebSocketHandler(), "/websocket").setAllowedOrigins("*"); } @Bean public WebSocketHandler myWebSocketHandler() { return new MyWebSocketHandler(); } } ``` 其中 `MyWebSocketHandler` 是自己实现的 WebSocket 消息处理类,可以在其中实现处理客户端发送过来的消息以及向客户端发送消息的逻辑。 下面是 `MyWebSocketHandler` 的一个示例: ``` public class MyWebSocketHandler extends TextWebSocketHandler { private Set<WebSocketSession> sessions = new CopyOnWriteArraySet<>(); @Override public void afterConnectionEstablished(WebSocketSession session) { sessions.add(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) { sessions.remove(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) { // 处理客户端发送过来的消息 } public void pushMessage(String message) { for (WebSocketSession session : sessions) { try { session.sendMessage(new TextMessage(message)); } catch (IOException e) { // 发送消息失败 } } } } ``` 在 `pushMessage` 方法中,可以遍历所有连接的客户端会话,向它们发送消息。 最后,在需要推送数据的地方,注入 `MyWebSocketHandler`,调用 `pushMessage` 方法即可: ``` @Autowired private MyWebSocketHandler webSocketHandler; public void sendData() { // 处理数据 webSocketHandler.pushMessage(data); } ``` 至此,我们就成功地在 Spring Boot 2.0整合WebSocket,并实现了服务器主动前端推送数据的功能。 ### 回答3: 随着现代web应用的流行,实时数据交换变得越来越重要,而websocket作为实时双向通信的技术,成为了重要的实时数据传输协议。Spring Boot2.0整合websocket可以让我们通过服务器主动前端推送数据,实现实时数据交换,满足现代web应用的高实时性需求。 WebSocket是一种基于HTTP协议的双向通信协议,在通信过程中,浏览器和服务器相互发送数据,实现实时数据交互。Spring Boot2.0已经内置了对WebSocket协议的支持,通过使用Spring WebSocket API可以很容易地配置WebSocket端点和处理程序。 服务器端可通过定义一个WebSocketConfig的配置类,配置WebSocket的Endpoint和Handler,并注册到拦截器链中,如下所示: @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSocketHandler(), "/ws").addInterceptors(new HttpSessionHandshakeInterceptor()); } @Bean public WebSocketHandler webSocketHandler() { return new MyWebSocketHandler(); } } 在MyWebSocketHandler中,通过实现WebSocketHandler接口的handleMessage方法,可以处理客户端发送来的消息。如下所示: public class MyWebSocketHandler implements WebSocketHandler { @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { //处理客户端发送来的消息 } } 服务器推送消息到前端,可以通过WebSocketSession的sendMessage方法实现,如下所示: session.sendMessage(new TextMessage("Hello,World!")); 客户端需要使用WebSocket API接收服务器推送来的数据,并处理数据,如下所示: var socket = new WebSocket("ws://localhost:8080/ws"); socket.onmessage = function(event) { //处理服务器推送过来的数据 }; 综上所述,Spring Boot2.0整合websocket可以通过配置WebSocket的Endpoint和Handler,在服务器主动前端推送数据,实现实时数据交换。对于现代web应用的高实时性需求,该技术具有重要意义。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值