Websocket
1.基本概念
WebSocket 是一种网络通信协议。
websocket和http 的区别,http的缺陷,只能从客户端发起请求(单项请求)不能从服务器发起请求。如果服务器有连续性的变化时,如果我们想要每一个时刻都获得最新的数据时,就需要不断的由客户端发起请求不停的发起连接,就会浪费很大一部分资源。
所以websocket的诞生就是为了解决之一问题,使得服务器也可以向客户端发起请求~实现网站实时推送的需求
websocket的特点:
1.建立在tcp协议之上
2.兼容http协议,握手阶段采用http协议。
3.数据格式轻量级,可以发送文本,还可以发送二进制数据
5.没有同源限制,客户端可以和任意服务器通信
协议标识:ws(加密后为wss
总结:websocket是一种网络协议,支持服务器与客户端的全双工连接。
websocket前端往后端发送数据,
socket.send("这是来自客户端的消息");
执行socket.send后对应着后端的WebSocketService.onMessage事件
websocket同时还定义了几个监听函数
1、onopen 当网络连接建立时触发该事件
2、onerror 当网络发生错误时触发该事件
3、onclose 当websocket被关闭时触发该事件
4、onmessage 当websocket接收到服务器发来的消息的时触发的事件。
在后端我们可以新建一个WebSocketService类来做整对websocket的以上四种状态来执行以下业务逻辑。
但在这之前需要导入websocket的依赖以及配置文件,很简单:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@Configuration
public class WebSocketConfig{
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
然后前端写的四个状态与后端定义的相对于
@Service
@ServerEndpoint("/imServer/{username}")
public class WebSocketService {
public static PlayerService playerService;
/**统计在线的人数*/
private static int onlineCount = 0;
/**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
private static ConcurrentHashMap<String,WebSocketService> webSocketMap = new ConcurrentHashMap<>();
/**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
private Session session;
/**接收userId*/
private String userId"";
@OnOpen
public void onOpen(Session session, @PathParam("username") String username){
}
@OnClose
public void onClose() throws IOException {
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
}
/**
* 通过遍历webSocketMap当前在线人数的session向每一个在线用户推送消息
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
for (String s : webSocketMap.keySet()) {
webSocketMap.get(s).session.getBasicRemote().sendText(message);
}
}
/**
* 发送自定义消息
* */
public static void sendInfo(String message,@PathParam("username") String toUsername) throws IOException {
if(webSocketMap.containsKey(toUsername)){
webSocketMap.get(toUsername).sendMessage(message);
}else{
System.out.println("用户"+toUsername+",不在线!");
}
}
public static synchronized void addOnlineCount() {
WebSocketService.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketService.onlineCount--;
}
public static synchronize int getOnlineCount() {
return onlineCount;
}
}
@ServerEndpoint("/imServer/{username}")则表示前端在新建websocket的连接时需要的url
对应这里我写的,前端代码就是:
let url="http://localhost:8082/imServer/"+username;
url=url.replace("https","ws").replace("http","ws");
socket =new WebSocket(url);
//打开事件
socket.onopen = function() {
};
//获得消息事件
socket.onmessage = function(msg) {
};
//关闭事件
socket.onclose = function(msg) {
};
//发生了错误事件
socket.onerror = function() {
}
后端业务可以通过sendMessage方法向前端传送数据:包括字符串、对象、二进制位、文件。
后端sendMessage传来的数据时就会执行socket.onmessage里面的代码