4.0.0org.springframework.bootspring-boot-starter-parent2.6.2com.czhwebsocket0.0.1-SNAPSHOTwebsocketDemo project for Spring Boot1.8org.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-starter-websocketorg.webjarswebjars-locator-coreorg.webjarssockjs-client1.1.2org.webjarsstomp-websocket2.3.3org.webjarsjquery3.3.1org.springframework.bootspring-boot-maven-plugin
配置websocket
package com.czh.websocket.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker//开启websocket消息代理
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS();
}
}
定义Controller
package com.czh.websocket.controller;
import com.czh.websocket.model.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class GreetingController {
@MessageMapping("hello")
@SendTo("/topic/greetings")
public Message greeting(Message message)throws Exception{
return message;
}
}