作者:lodng | 来源:互联网 | 2023-10-11 12:05
后端代码:publicclassWebSocketConfigimplementsWebSocketMessageBrokerConfigurer{publicvo
后端代码:
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {public void registerStompEndpoints(StompEndpointRegistry registry) {registry.addEndpoint("/daoshu/socket").setAllowedOrigins("*")//添加允许跨域访问.withSockJS() ;}public void configureMessageBroker(MessageBrokerRegistry registry) {registry.enableSimpleBroker("/daoshu/socket/send","/user/");//推送消息前缀registry.setApplicationDestinationPrefixes("/daoshu/socket/req");//应用请求前缀registry.setUserDestinationPrefix("/user");//推送用户前缀}@Overridepublic void addArgumentResolvers(List arg0) {}@Overridepublic void addReturnValueHandlers(List arg0) {}@Overridepublic void configureClientInboundChannel(ChannelRegistration arg0) {}@Overridepublic void configureClientOutboundChannel(ChannelRegistration arg0) {}@Overridepublic boolean configureMessageConverters(List arg0) {return false;}@Overridepublic void configureWebSocketTransport(WebSocketTransportRegistration arg0) {}}
public class WebSocketController {@Resourceprivate SimpMessagingTemplate messagingTemplate;private Timer timer;private static int imgIndex = 0;private final String[] imgList = { "0.png", "1.png", "2.png", "3.png", "4.png", "5.png", "6.png" };@RequestMapping("/index")public String index() {return "index";}@MessageMapping("/message")public ResponseMessage toUser(RequestMessage msg) {timer = new Timer(true);long delay = 0;OrderTimeTask orderTimeTask = new OrderTimeTask(msg.getMessage());timer.schedule(orderTimeTask, delay, 2000);// 设定指定的时间time,此处为5sreturn new ResponseMessage("欢迎使用webScoket:" + msg.getMessage());}@ResponseBody@RequestMapping("/cancel")public ResponseMessage cancelTimer(HttpServletRequest request) {if (null != timer) {imgIndex = 0;timer.cancel();}return new ResponseMessage("关闭成功");}class OrderTimeTask extends TimerTask {private String message;public OrderTimeTask(String message) {this.message = message;}@Overridepublic void run() {try {String imgPath = imgList[imgIndex];TextMessage textMessage;if (imgIndex == 0) {textMessage = new TextMessage(message);} else {textMessage = new TextMessage(imgPath);}messagingTemplate.convertAndSendToUser("gis", "/message", textMessage.getPayload());imgIndex++;if (imgIndex == imgList.length)imgIndex = 0;} catch (Exception e) {e.printStackTrace();}}}}
前端代码:
<%&#64; page contentType&#61;"text/html;charset&#61;UTF-8" language&#61;"java"%>