spring websocket让页面实时获取数据

1,依赖包加上

            org.springframework
            spring-websocket
        
        
            org.springframework
            spring-messaging

2,添加2个类

package com.streetlight.websocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/socket").withSockJS();
	}

	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		registry.enableSimpleBroker("/topic");//给 /topic 命名空间下发数据
		registry.setApplicationDestinationPrefixes("/app");//客户端发向服务端请求路径的前缀
	}
}

package com.streetlight.websocket;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class WebSocketController {
	@MessageMapping("/request")//接受客户端/app/request的请求
	@SendTo("/topic/*")
	public String greeting() throws Exception {
		return new String("WebSocketController");
	}
}
然后需要一个发送模版, 如下

@Compent
public class Handler{

    @Autowired
    private SimpMessagingTemplate mesTemp;

    public void updateAndSendMsg() {
        mesTemp.convertAndSend("/topic/hello", "helloworld");
    }
}
这时候在网页上需要添加连接websocket  server的代码

        
当连接上server后stompClient.subscribe会监听和接受来自‘/topic/hello’的数据


到这里就配置完成了!我这边是java程序收设备发过来的UDP消息,一收到消息就调用Handler类中的updateAndSendMsg方法!

推荐个发包程序:netAssistant


参考 : http://www.lxway.com/4002114921.htm

你可能感兴趣的:(spring websocket让页面实时获取数据)