1、第一步需要在pom.xml中添加 websocket 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、第二步添加 ServerEndpointExporter Bean配置
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、第三步新建 WebSocketServer 对外服务
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.dbappsecurity.utils.concurrent.ThreadPoolUtil;
import com.dbappsecurity.utils.domain.WebSocketMsgDTO;
import lombok.extern.slf4j.Slf4j;
@ServerEndpoint(value = "/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {
private static AtomicLong count = new AtomicLong(0);
public static ConcurrentHashMap<Long, WebSocketServer> map = new ConcurrentHashMap<>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(@PathParam("userId") Long userId, Session session) {
// TODO 判断 userId 是否为已登录用户,如果不是,则说明发生入侵
this.session = session;
map.put(userId, this);
addOnlineCount();
log.info("有新连接加入: [{}], 当前在线人数为 [{}]", userId, getOnlineCount());
try {
session.getBasicRemote().sendText("Connected.");