我想在我的Spring项目中使用Web套接字。我配置了网络套接字并从另一个控制器调用它,但是有些不起作用。我也经常提到spring doc https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#websocket。 配置是:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@CrossOrigin
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/Track").withSockJS();
}
}
我的控制器是我打电话的地方,还创建了一些Web套接字:
@Controller
@ComponentScan(value="com.demo.websocket")
public class UserControllerWS {
@Autowired(required=true)
private SimpMessagingTemplate simpMessagingTemplate;
Logger logger = LoggerFactory.getLogger(UserControllerWS.class);
@MessageMapping("/user")
@SendToUser("/topic/users")
public List<User> getUser(
@Payload UserDto userDto){
System.out.println("----------------------");
System.out.println("Event triggerd At User");
System.out.println("----------------------");
System.out.println(new Gson().toJson(userDto));
return null;
}
@RequestMapping(value="/demo",method=RequestMethod.GET)
public void mainTask() {
System.out.println("-----------------------------------");
System.out.println("-----------------------------------");
UserDto userDto=new UserDto();
this.simpMessagingTemplate.convertAndSend("/user", userDto);
this.simpMessagingTemplate.convertAndSend("/topic/users", userDto);
System.out.println("-----------------------------------");
System.out.println("-----------------------------------");
}
}
答案 0 :(得分:0)
您需要修改控制器。只需为构造器自动布线。
@Controller
public class WebSocketController {
private final SimpMessagingTemplate template;
@Autowired
WebSocketController(SimpMessagingTemplate template){
this.template = template;
}
@MessageMapping("/send/message")
public void onRecievedMessage(String message){
this.template.convertAndSend(
"/chat",message);
}
}