热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

websocket定时推送

后端代码: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"%>








输入名称&#xff1a;




 

 

 

 

 

 

 

 

 


推荐阅读
author-avatar
lodng
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有