1、简介
WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议,使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。这里介绍websocet推送给指定的人群,以及全部用户的方式。同时本文介绍的为使用@ServerEndpoint
接口来实现消息的推送,其他的推送方式,可以参考本文最后一个参考文章,本文中方法使用较为简单易懂,可用性没有测试过,但是看着公司也在用这种方式,最近又在写这方面的需求,因此在这简单判断为具有一定的可用性吧。
一般socket的推送,中间件的消息订阅之类的,会结合监听方法的使用ApplicationListener来进行使用,有时间大家学习一下,这部分内容后面会补充上来,代码也会上传。
WebSocket消息推送流程:
2、WebSocket推送
2.1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.2、创建配置类
注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint。
package com.example.studydemo.socket;
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();
}
}
2.3、创建连接类
在这里可以先熟悉一下里面各种原生注解的方法。当前端进行websocket连接之后,该类中的@OnOpen所注解的方法便会执行,如同接口调用的一致。在此方法中你可以进行一系列的业务操作,用于后续的使用。@OnClose所注解的方法在session断开之后,或者前端断开连接后,便会触发此方法。其他注解不做过多的解释。
【注意】:代码中 :消息的推送同步还是异步根据自己的选择来。
session.getBasicRemote().sendText(msg);
这个为消息的同步推送
session.getAsyncRemote().sendText(msg);
这个为消息的异步推送
package com.example.studydemo.socket;
import com.alibaba.druid.support.json.JSONUtils;
import com.rabbitmq.tools.json.JSONUtil;
import io.netty.handler.codec.json.JsonObjectDecoder;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONObject;
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.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
@Component
@ServerEndpoint(value = "/serverForWebSocket/{userId}")
public class Server4WebSocket {
// 存储登录用户的 sid 以及 session
private static ConcurrentHashMap<String, Session> connections = new ConcurrentHashMap<>(32);
private Session session; // 是WebSocket的Session
// 统计在线人数
private static AtomicInteger onlineCount = new AtomicInteger();
@OnOpen //事件 --登录的人.//当你登录之后建立连接,此方法便会执行
public void onopen(@PathParam("userId") String userId, Session session) {
this.session = session;
System.out.println("seesionId为" + session.getId());
if (connections.containsKey(userId)) {
connections.remove(userId);
connections.put(userId, session);
}else {
onlineCount.incrementAndGet();
connections.put(userId, session);
System.out.println("用户:"+userId+"-"+session.getId()+"上线了-"+session);
System.out.println("在线人数:"+onlineCount);
}
String content = new JSONObject(connections).toString();
System.out.println("在线用户信息:" + content);
}
@OnClose
public void onClose(Session session){
for (String userId : connections.keySet()) {
if(connections.get(userId).equals(session)){
System.out.println("用户:"+userId+"-关闭-"+session);
connections.remove(session);
onlineCount.decrementAndGet(); // 在线数减1
}
}
}
@OnMessage
public void onMessage(String msg, Session session) {
System.out.println("服务端收到客户端"+session.getId()+"的消息:"+msg);
// 客户端向服务端发送消息,然后再推送给其他的用户,可以在这里进行设置
try {
sendMessage(msg, session);
} catch (IOException e) {
e.printStackTrace();
}
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
//推送
public void sendMessage(String msg, Session session) throws IOException {
// for (Session session1 : webSocketSet) {
// if (session != session1)
// session1.getBasicRemote().sendText(msg);
// }
System.out.println("推送:"+msg);
session.getBasicRemote().sendText(msg);
}
// 推送给指定的用户群
public void sendMsgToUsers(List<String> ids) {
ids.stream().forEach(s -> {
System.out.println("用户:"+s+"是否能够推送:"+connections.containsKey(s));
if (connections.containsKey(s)) {
if (connections.get(s).isOpen()){
try {
System.out.println("开始推送");
sendMessage("hello:"+s,connections.get(s));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
});
}
// 推送给全部在线用户
public void sendMsgToAll(){
connections.keySet().stream().forEach(s->{
if (connections.get(s).isOpen()){
try {
System.out.println("开始推送");
sendMessage("hello:"+s,connections.get(s));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
}
2.4、调用类
代码的宗旨:简洁、有效、高内聚、低耦合。因此需要业务层等,这里来不及规范书写,莫怪,哈!
package com.example.studydemo.socket;
import java.util.List;
public class WebSocketService {
// 推送给指定的在线的用户
public void sendMsgToUsers(List<String> ids) {
Server4WebSocket server4WebSocket = new Server4WebSocket();
server4WebSocket.sendMsgToUsers(ids);
}
}
2.5、Controller层
需要推送的接口,需要相应的业务的自己进行编写即可。
package com.example.studydemo.controller;
import com.example.studydemo.common.core.controller.BaseController;
import com.example.studydemo.common.core.domain.AjaxResult;
import com.example.studydemo.socket.WebSocketService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
@RestController
@RequestMapping("/socketTestController")
public class SocketTestController extends BaseController {
@PostMapping("/push")
public AjaxResult push() {
// 模拟需要推送的用户群
ArrayList<String> ids = new ArrayList<>();
ids.add("001");
ids.add("002");
ids.add("003");
ids.add("004");
ids.add("005");
WebSocketService webSocketService = new WebSocketService();
webSocketService.sendMsgToUsers(ids);
return AjaxResult.success("推送成功");
}
}
2.6、前端
使用简单的HTML测试即可。具体的含义看下注解,简单易懂。
<!DOCTYPE html>
<html lang="en">
<head>
<title>net My WebSocket</title>
</head>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
//连接WebSocket节点
websocket = new WebSocket("ws://localhost:8080/serverForWebSocket/001");
window.websocket = websocket;
} else {
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function (event) {
setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭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;
console.log(message);
websocket.send(message);
}
</script>
<body>
TestWebSocket
<input id="text" type="text"/>
<input type="submit" onclick="send()">
<button οnclick="closeWebSocket()">CLOSE</button>
<div id="message"></div>
</body>
</html>
3、测试
在桌面建立两个html文件,里面的id不要相同。
使用edge浏览器模拟用户001:
使用google浏览器模拟用户003
文章参考:
https://blog.csdn.net/u011174699/article/details/108676434
https://blog.csdn.net/Funny2333/article/details/115756441
https://blog.csdn.net/chenduxiu666/article/details/124497356