spring websocket让页面实时获取数据

1,依赖包加上
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
</dependency>

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的代码

        <script type="text/javascript">
        $(function(){
            var socket = new SockJS('/项目名/socket');
            var stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {//
                stompClient.subscribe('/topic/hello', function(message){//注意这里的'/topic/hello'与上面Handler类updateAndSendMsg方法中的一样
                    console.log("msg :" + message)
                });
            });
        })
        </script>
当连接上server后stompClient.subscribe会监听和接受来自‘/topic/hello’的数据


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

推荐个发包程序:netAssistant


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

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭