依赖
<!--websocket--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
配置类
@Configuration
public class WebSocketConfig {@Bean //方法返回值交给springboot管理public ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}
前端发送格式
ws://127.0.0.1:8080/chat/123456
123456为用户ID
{"id":"123456", //后端需要根据这个id回复"msg":"123" //前端发送的内容
}
收发消息
@ServerEndpoint("/chat/{id}") //请求路径
@Component
public class WebChat {private static final Map<String,Session> sessionMap = new ConcurrentHashMap<>() ;//存取用户@OnOpen //用户连接时public void onOpen(Session session,@PathParam(value = "id") String id){sessionMap.put(id,session); //用户连接成功 保存用户信息}@OnMessage //用户收到信息时public void onMessage(String message) {JSONObject jsonObject = JSON.parseObject(message);String id =jsonObject.getString("id"); //用户idString msg =jsonObject.getString("msg"); //用户发送的信息Session session =sessionMap.get(id);//根据id获取Sessionsession.getAsyncRemote().sendText("已收到消息,你的ID是"+id); //回复消息}public void sendMessage(String id,String message){Session session= sessionMap.get(id);session.getAsyncRemote().sendText(id);}@OnClosepublic void onClose(){}