该文章只是简单实现全双工 后台向前台推送消息,没有深入理解请见谅
废话不都说,直接上代码
一.引入webscoket的包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二.配置websocket 前后台都要配置
前台代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="request">发送请求......</button>
<div id="value">
</div>
<div id="message">
</div>
</body>
<script th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
<script type="text/javascript">
let websocket = null;
//判断浏览器是否支持websocket
if('WebSocket' in window){
// 建立socket连接
websocket = new WebSocket("ws://localhost:8083/connectWebSocket");
}else {
alert("view page dosnt support websoket")
}
//连接成功回调函数
websocket.onopen = function(){
console.log("已成功连接!")
}
//连接关闭回调函数
websocket.onclose = function(){
websocket.close();
}
//接收消息回调函数
websocket.onmessage = function(event) {
$("#value").empty();
console.log("接收到服务端返回的消息.................")
console.log('实时返回的数据是======>',event.data)
$("#value").append("<div>"+event.data+"</div>");
}
//监听窗口关闭事件
window.onbeforeunload = function(){
websocket.close();
}
//连接错误回调函数
websocket.onerror = function(){
setMessageInnerHTML("error")
}
//将消息展示在网页上
function setMessageInnerHTML(message){
document.getElementById('message').innerHTML += message + '</br/>';
}
//关闭连接函数
function close(){
websocket.close();
}
//发送消息
function send(){
let msg = document.getElementById('text').value;
//从客户端向服务端发消息
websocket.send(msg);
}
$(function () {
$("#request").click(function () {
//发送请求
$.get("/test",function (res) {
console.log(res.result)
})
})
})
</script>
</html>
后台代码
1.在启动类中配置bean---ServerEndpointExporter
package com.wt.websocket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
*
* 后台向前台实时推送数据
*
*
*/
@SpringBootApplication
@EnableScheduling
public class WebsocketApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketApplication.class, args);
}
//这个bean的注册,用于扫描带有@ServerEndpoint的注解成为websocket ,如果你使用外置的tomcat就不需要该配置文件
@Bean
public ServerEndpointExporter serverEndpointExporter()
{
return new ServerEndpointExporter();
}
}
2.创建socket配置类
package com.wt.websocket.SocketConfig;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
@ServerEndpoint(value = "/connectWebSocket")//这里的路径注意一下 我只是为了测试 就没有写参数了
public class WebSocket {
private Logger logger = LoggerFactory.getLogger(this.getClass());
//concurrent包的线程安全Set,用来存放每个客户端对应的Socket对象。
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<WebSocket>();
/**
* 会话
*/
private Session session;
/**
* 用户名称
*/
private String userId;
/**
* 建立连接
*
* @param session
*/
@OnOpen
public void onOpen( Session session) {
this.session = session;
webSockets.add(this);
}
@OnError
public void onError(Session session, Throwable error) {
logger.info("服务端发生了错误"+error.getMessage());
}
/**
* 连接关闭
*/
@OnClose
public void onClose() {
webSockets.remove(this);
}
/**
* 接收客户端的消息
*
* @param message 消息
* @param session 会话
*/
@OnMessage
public void onMessage(String message, Session session) {
try{
//收到客户端消息后调用的方法
for (WebSocket item : webSockets) {
item.sendMessage(message);
}
}catch (Exception e){
}
}
/**
* @author: wt
* @date: 2019/12/24
* @description:向单个客户端推送消息
*/
public void sendMessage(String message){
try{
this.session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @author: wt
* @date: 2019/12/24
* @description:群发消息
*/
public static void sendInfoToAll(String message){
for (WebSocket item : webSockets) {
//这里全部推送,单独发送需要判断sid
item.sendMessage(message);
}
}
}
3.最后写一个定时任务
@RequestMapping("/test")
@Scheduled(fixedRate = 3000) //定时任务 每三秒执行一次 向前台推送信息
public Map index(){
System.err.println("被请求了.........");
Map<String,Object> resultmap=new HashMap<>();
resultmap.put("result",new Date());
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
push(simpleDateFormat.format(new Date()));
return resultmap;
}
三.结果
四.结语
只要浏览器和后台建立一次成功的连接后,后台就能主动的向前台推送消息,而不用前台请求后台