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:
错误原因:Chrome的autoplay政策在2018年4月做了更改。
解决办法:
第一步,在chrome浏览器中输入:chrome://flags/#autoplay-policy
第二步,在Autoplay policy中将Default改为No user gesture is required
第三步,点击下方的“RELAUNCH NOW”,就大功告成了!