引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置类
- 基本配置类
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();
}
}
- 获取HttpSession对象配置类
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
public class GetHttpSessionConfig extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
// 获取HttpSession对象
HttpSession httpSession = (HttpSession) request.getHttpSession();
// 将HttpSession对象保存起来
sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
@ServerEndpoint(value = “/chat”,configurator =
GetHttpSessionConfig.class
)
要在@ServerEndpoint注解的属性中添加该类对象
代码
import com.example.mybatisplusdemo.config.GetHttpSessionConfig;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfig.class)
public class RobotWebsocket {
public static final Map<String,Session> onlineUsers = new ConcurrentHashMap<>();
private HttpSession httpSession;
private String user;
@OnOpen
public void onOpen(Session session, EndpointConfig config){
httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
user = (String) httpSession.getAttribute("user"); // 与登录成功时保存的key一致
onlineUsers.put(user,session);
// 广播消息
broadcastAllUser(user + "上线了");
}
public Set getFriends(){
return onlineUsers.keySet();
}
private void broadcastAllUser(String message) {
try {
Set<Map.Entry<String, Session>> entries = onlineUsers.entrySet();
for (Map.Entry<String, Session> entry : entries) {
Session session = entry.getValue();
session.getBasicRemote().sendText(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@OnMessage
public void onMessage(String message){
broadcastAllUser(user + " :" + message);
}
@OnClose
public void onClose(Session session){
onlineUsers.remove(user); // 剔除用户
broadcastAllUser(user + "下线了");
}
}