很多网站为了实现推送技术,所用的技术都是轮询。轮询是在特定的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。
而比较新的技术去做轮询的效果是Comet。这种技术虽然可以双向通信,但依然需要反复发出请求。而且在Comet中,普遍采用的长链接,也会消耗服务器资源。
在这种情况下,HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。
首选需要配置一个客户端的实体类
package com.example.websocket.entity;
import lombok.Data;
import javax.websocket.Session;
import java.time.LocalDateTime;
/**
* 客户端实体类
*
* @author abdul
* @since 2024/08/29 19:50
*/
@Data
public class ClientInfoEntity {
/**
* 客户端唯一标识
*/
private String token;
/**
* 客户端连接的session
*/
private Session session;
/**
* 连接存活时间
*/
private LocalDateTime existTime;
}
创建 ChatEndpoint2 该类负责监听客户端的连接、断开连接、接收消息、发送消息等操作
package com.example.websocket.util;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.easyExcel.exception.ExcelException;
import com.example.websocket.config.GetHttpSessionConfig;
import com.example.websocket.entity.ClientInfoEntity;
import com.example.websocket.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 该类负责监听客户端的连接、断开连接、接收消息、发送消息等操作。
*
* @author abdul
* @since 2024/08/29 19:50
*/
@Slf4j
@Component
@CrossOrigin(origins = "*")
@ServerEndpoint(value = "/webSocket/{token}", configurator = GetHttpSessionConfig.class)
public class ChatEndpoint2 {
//key:客户端连接唯一标识(token)
//value:ClientI