WebSockeet
1.简历
是基于TCP的一种新的网络协议,实现了浏览器与服务器全双工通信–允许服务器主动发送信息给客户端
2.为什么使用WebSocket
HTTP是基于请求响应的,即通信只能由客户端发起,服务端做出响应,无状态,无连接
WebSocket最大的特点就是服务器可以主动向客服端发送信息,客户端也可以向服务器发送信息
(1)建立在 TCP 协议之上,服务器端的实现比较容易。
(2)与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
(3)数据格式比较轻量,性能开销小,通信高效。
(4)可以发送文本,也可以发送二进制数据。
(5)没有同源限制,客户端可以与任意服务器通信。
(6)协议标识符是ws(如果加密,则为wss),服务器网址就是 URL
3.使用
1.依赖
<!-- websocket dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.7.12</version>
</dependency>
2.配置
/**
* WebSocket配置类。开启WebSocket的支持
*/
@Configuration
public class WebSocketConfig {
/**
* bean注册:会自动扫描带有@ServerEndpoint注解声明的Websocket Endpoint(端点),注册成为Websocket bean。
* 要注意,如果项目使用外置的servlet容器,而不是直接使用springboot内置容器的话,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.使用
-
因为WebSocket是类似客户端服务端的形式(
采用ws协议
),那么这里的WebSocketServer其实就相当于一个ws协议的Controller, -
@Component和@ServerEndpoint关于是否单例模式,能否使用static Map等一些问题的解答
看到大家都在热心的讨论关于是否单例模式这个问题,请大家相信自己的直接,如果websocket是单例模式,还怎么服务这么多session呢。websocket是原型模式,@ServerEndpoint每次建立双向通信的时候都会创建一个实例,区别于spring的单例模式。
Spring的@Component默认是单例模式,请注意,默认 而已,是可以被改变的。
这里的@Component仅仅为了支持@Autowired依赖注入使用,如果不加则不能注入任何东西,为了方便。
什么是prototype 原型模式? 基本就是你需要从A的实例得到一份与A内容相同,但是又互不干扰的实例B的话,就需要使用原型模式。
关于在原型模式下使用static 的webSocketMap,请注意这是ConcurrentHashMap ,也就是线程安全/线程同步的,而且已经是静态变量作为全局调用,这种情况下是ok的,或者大家如果有顾虑或者更好的想法的化,可以进行改进。 例如使用一个中间类来接收和存放session。@OnOpen开启连接,@onClose关闭连接,@onMessage接收消息等方法。
-
private Session session; /** * 存放所有在线的客户端 */ private static Map<String, Session> onlineSessionClientMap = new ConcurrentHashMap<>();
注解@ServerEndpoint:
类似于RequestMapping映射ws协议访问的url,标识在类上
直接@ServerEndpoint(“/imserver/{userId}”) 、@Component启用即可(!!必须)
以下返回值都是void
@OnOpen
标识与建立连接的方法上,当建立连接时候试行该方法
@onClose
标识与建立在关闭的方法上,当关闭连接时候试行该方法的内容
@onMessage接收消息
接受来自客户端发送的消息是一个json数据,进行获取json对象值
进行执行方法
@OnError
当连接错误时执行的方法
Session.getAsyncRemote().sendText(message)方法
选择session来发送信息给客户端
4.前端使用
创建WebSocket对象
var reqUrl = “http://localhost:8081/websocket/” + cid(对应@ServerEndpoint中的内容);
socket = new WebSocket(reqUrl.replace(“http”, “ws”));(ws协议)
socket.onopen -----------------建立连接事件
socket.onmessage= function (msg)-----------------获取服务器端信息事件
socket.onclose = function -----------------关闭连接的事件
socket.onerror-------------错误事件
socket.send(msg);-------------向服务器端发送内容
var msg = ‘{“sid”:"’ + toUserId + ‘“,“message”:”’ + contentText + ‘"}’;
5.案例
配置
@Configuration
@EnableWebSocket
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
映射
@Component
@ServerEndpoint("/websocket/{sid}")//接口路径 类似RequestMapping
public class WebSocket {
/**
* 静态变量,用来记录当前在线连接数,线程安全的类。
*/
private static AtomicInteger onlineSessionClientCount = new AtomicInteger(0);
/**
* 存放所有在线的客户端
*/
private static Map<String, Session> onlineSessionClientMap = new ConcurrentHashMap<>();
/**
* 连接sid和连接会话
*/
private String sid;
private Session session;
/**
* 连接建立成功调用的方法。由前端<code>new WebSocket</code>触发
*
* @param sid 每次页面建立连接时传入到服务端的id,比如用户id等。可以自定义。
* @param session 与某个客户端的连接会话,需要通过它来给客户端发送消息
*/
@OnOpen
public void onOpen(@PathParam("sid") String sid, Session session) {
/**
* session.getId():当前session会话会自动生成一个id,从0开始累加的。
*/
System.out.println("连接建立中 ==> session_id = {}, sid = {}"+ session.getId()+sid);
//加入 Map中。将页面的sid和session绑定或者session.getId()与session
//onlineSessionIdClientMap.put(session.getId(), session);
onlineSessionClientMap.put(sid, session);
//在线数加1
onlineSessionClientCount.incrementAndGet();
this.sid = sid;
this.session = session;
sendToOne(sid, "连接成功");
System.out.println ("连接建立成功,当前在线数为:{} ==> 开始监听新连接:session_id = {}, sid = {},。" +
""+ onlineSessionClientCount+session.getId()+sid);
}
/**
* 连接关闭调用的方法。由前端<code>socket.close()</code>触发
*
* @param sid
* @param session
*/
@OnClose
public void onClose(@PathParam("sid") String sid, Session session) {
//onlineSessionIdClientMap.remove(session.getId());
// 从 Map中移除
onlineSessionClientMap.remove(sid);
//在线数减1
onlineSessionClientCount.decrementAndGet();
System.out.println("连接关闭成功,当前在线数为:{} ==> 关闭该连接信息:session_id = {}, sid = {},。" +
""+onlineSessionClientCount+ session.getId()+ sid);
}
/**
* 收到客户端消息后调用的方法。由前端<code>socket.send</code>触发
* * 当服务端执行toSession.getAsyncRemote().sendText(xxx)后,前端的socket.onmessage得到监听。
*
* @param message
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) throws JSONException {
/**
* html界面传递来得数据格式,可以自定义.
* {"sid":"user-1","message":"hello websocket"}
*/
JSONObject jsonObject = JSON.parseObject(message);
String toSid = jsonObject.getString("sid");
String msg = jsonObject.getString("message");
System.out.println("服务端收到客户端消息 ==> fromSid = {}, toSid = {}, message = {}"+sid+toSid+message);
/**
* 模拟约定:如果未指定sid信息,则群发,否则就单独发送
*/
if (toSid == null || toSid == "" || "".equalsIgnoreCase(toSid)) {
sendToAll(msg);
} else {
sendToOne(toSid, msg);
}
}
/**
* 发生错误调用的方法
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("WebSocket发生错误,错误信息为:" + error.getMessage());
error.printStackTrace();
}
/**
* 群发消息
*
* @param message 消息
*/
private void sendToAll(String message) {
// 遍历在线map集合
onlineSessionClientMap.forEach((onlineSid, toSession) -> {
// 排除掉自己
if (!sid.equalsIgnoreCase(onlineSid)) {
System.out.println("服务端给客户端群发消息 ==> sid = {}, toSid = {}, message = {}"+sid+onlineSid+ message);
toSession.getAsyncRemote().sendText(message);
}
});
}
/**
* 指定发送消息
*
* @param toSid
* @param message
*/
private void sendToOne(String toSid, String message) {
// 通过sid查询map中是否存在
Session toSession = onlineSessionClientMap.get(toSid);
if (toSession == null) {
System.out.println("服务端给客户端发送消息 ==> toSid = {} 不存在, message = {}"+ toSid+ message);
return;
}
// 异步发送
System.out.println("服务端给客户端发送消息 ==> toSid = {}, message = {}"+ toSid+ message);
toSession.getAsyncRemote().sendText(message);
}
}
前端
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>666666</title>
</head>
<body>
传递来的数据值cid:
<input type="text" th:value="${cid}" id="cid"/>
<p>【toUserId】:
<div><input id="toUserId" name="toUserId" type="text" value="user-1"></div>
<p>【toUserId】:
<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】:
<div>
<button type="button" onclick="sendMessage()">发送消息</button>
</div>
<div id="div"></div>
</body>
<script type="text/javascript">
let socket;
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
let cid = document.getElementById("cid").value;
console.log("cid-->" + cid);
let reqUrl = "http://localhost:8080/websocket/" + cid;
socket = new WebSocket(reqUrl.replace("http", "ws"));
//打开事件
socket.onopen = function () {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
let div = document.getElementById('div')
div.innerHTML += msg.data + "<br/>";
console.log("onmessage--" + msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function () {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
function sendMessage() {
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
// console.log("您的浏览器支持WebSocket");
var toUserId = document.getElementById('toUserId').value;
var contentText = document.getElementById('contentText').value;
var msg = '{"sid":"' + toUserId + '","message":"' + contentText + '"}';
console.log(msg);
socket.send(msg);
}
}
</script>
</html>
// console.log(“您的浏览器支持WebSocket”);
var toUserId = document.getElementById(‘toUserId’).value;
var contentText = document.getElementById(‘contentText’).value;
var msg = ‘{“sid”:"’ + toUserId + ‘“,“message”:”’ + contentText + ‘"}’;
console.log(msg);
socket.send(msg);
}
}
# 扩展Redis发布订阅功能