ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
**1. 五种监听事件** ```java @Component public class ConnectListener implements ApplicationListener<SessionConnectEvent> { @Override public void onApplicationEvent(SessionConnectEvent event) { System.out.println("正在建立连接."); } } @Component public class ConnectedListener implements ApplicationListener<SessionConnectedEvent> { @Override public void onApplicationEvent(SessionConnectedEvent event) { System.out.println("已经建立连接."); } } @Component public class SubscribeListener implements ApplicationListener<SessionSubscribeEvent> { @Override public void onApplicationEvent(SessionSubscribeEvent event) { System.out.println("正在订阅消息."); //我们可以从StompHeaderAccessor中拿到很多的信息,比如请求地址,请求类型等 StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage()); System.out.println(accessor.getDestination()); ///topic/v1/chat } } @Component public class UnsubscribeListener implements ApplicationListener<SessionUnsubscribeEvent> { @Override public void onApplicationEvent(SessionUnsubscribeEvent sessionUnsubscribeEvent) { System.out.println("已取消订阅."); } } @Component public class DisconnectListener implements ApplicationListener<SessionDisconnectEvent> { @Override public void onApplicationEvent(SessionDisconnectEvent sessionDisconnectEvent) { System.out.println("已经断开连接."); } } ``` **2. 前端代码** 当前端进行不同的操作时,上面的5中监听器就会相应的被调用。 ```js <script type="text/javascript"> var client = null function connect() { const socket = new SockJS('http://localhost:8083/endpoint-websocket') client = Stomp.over(socket) client.connect({}, (frame) => { console.info('已经建立连接.', frame) }) } function sendWithsubscribe() { client.send('/app/v1/chat', {}, 'Hello World!') client.subscribe('/topic/v1/chat', (res) => { console.info(res.body) }) } function unsubscribe() { client.unsubscribe('/topic/v1/chat') } function disconnect() { client.disconnect() } </script> ```