1.pom文件加入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
2.编写配置类,在你项目内新建一个包util,创建一个类WebSocketConfig
把下面代码复制
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.在controller包内创建新的类叫MyWebSocket复制下面代码即可
package com.hhy.cache.controller;
/**
* @author hhy
* @date 2020/8/13 - 9:44
*/
import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private String name;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入:"+"!当前在线人数为" + getOnlineCount());
try {
sendMessage("连接成功,当前时间:" + new java.sql.Timestamp(System.currentTimeMillis()));
} catch (IOException e) {
System.out.println("IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session,@PathParam("sname") String sname) {
System.out.println("来自客户端"+name+"的消息:" + message);
//群发消息
for (MyWebSocket item : webSocketSet) {
try {
item.sendMessage(message);
System.out.println("推送消息给:"+item.name+",消息是===》"+message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发生错误时调用
* */
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 服务端给客户端发送消息
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText("服务端回应消息:"+message+"------------->"+"服务器推送消息");
//this.session.getAsyncRemote().sendText(message);
}
public void sendMessage1(String message){
for (MyWebSocket webSocket: webSocketSet) {
System.out.println("【websocket消息】广播消息, message={}"+message);
try {
webSocket.session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 群发自定义消息
* */
public static void sendInfo(@PathParam("sname") String sname,String message) throws IOException {
for (MyWebSocket item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sname==null) {
item.sendMessage(message);
System.out.println("推送消息给:"+item.name+",消息是===》"+message);
}else if(item.name.equals(sname)){
item.sendMessage(message);
System.out.println("推送消息给:"+item.name+",消息是===》"+message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}
4.websocket前端页面编写,本页面和后端代码是我拿别人小项目改造了一下的,姓名可以不用输入,进入页面即可触发websocket
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
<script src="../js/jquery.min.js"></script>
</head>
<body>
Welcome <input id="name" type="text" /><button onclick="concat()">concat</button><br/>
<input id="text" type="text" /><button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
// function concat() {
// var name = document.getElementById('name').value;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8084/websocket");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("socket连接失败");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("socket连接已打开");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
console.log("收到消息" + event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("socket连接已关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
// }
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML +"<br/>";
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
/* function send(){
$.ajax({
url: '/user/selectUser.do',
dataType: 'json',
async: false,
success: function (data) {
console.log(data);
for(var i=0;i<data.length;i++){
websocket.send(data[i].name);
}
}
});
}*/
// 检测浏览器支持
// if (typeof(Storage) !== "undefined") {
// document.getElementById("result").innerHTML = sessionStorage.getItem("lastname");
// } else {
// document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
// }
</script>
</html>
5.太复杂了,给源码你自己改造吧。
记得改项目配置文件的数据库密码和账户,这个源码是我改造了的,
sendMessage1(String message)这个才是群发消息,sendMessage(String message)是客户第一次进入发送消息,我indexcontroller设置了定时任务,不用你记得删了。
链接:https://pan.baidu.com/s/1XUPMS0oI8GCB5Kg5lBlEfA
提取码:8ygk