spring web socket服务器和反应客户端

时间:2017-05-04 08:09:43

标签: spring spring-boot spring-websocket sockjs spring-web

我必须开发一个带有弹簧的Web套接字服务器,每隔5秒向客户端发送一条消息。客户端用react js编写。这是我的服务器代码:

@SpringBootApplication
@EnableAsync
@EnableScheduling
public class TestwsApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestwsApplication.class, args);
    }
}



@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
    }

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

这是我的调度程序,每隔5秒向频道/主题/消息发送一条消息

@Component
public class ScheduledTasks {

    @Autowired
    WebSocketListener listener;

    int i=0;

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {

        if (i==0){

            listener.pushSystemStatusToWebSocket("ok");
            i=1;
        }else{
            listener.pushSystemStatusToWebSocket("errore");
            i=0;
        }



    }
}

这是我的调度程序用来将消息发送到客户端的服务

    @Service
public class WebSocketListener {

    @Autowired
    private SimpMessagingTemplate webSocket;


    @Async
    public void pushSystemStatusToWebSocket (String newStatus){
        System.out.println("inviooooooooooooooooooooooooooo");

        webSocket.convertAndSend("/topic/messages", newStatus);
    }

}

这是我的反应组件

import SockJS from 'sockjs-client';

class Main extends React.Component {
    constructor() {
        super();
        this.state = {
            clickCount: 0,
        };
    }
    componentDidMount(){
        // this is an "echo" websocket service
        console.log('didmount')
        var sock = new SockJS('http://localhost:8080/chatWS');


        sock.onopen = function() {
            console.log('open socket ');
            sock.send('test');
        };

        sock.onmessage = function(e) {
            console.log('message');
            console.log('message', e.data);
            sock.close();
        };

        sock.onclose = function() {
            console.log('close');
        };
    }

在日志中我只看到帖子打开套接字...我没有看到任何日志插入onmessage ...所以客户端没有收到消息。为什么?你能帮助我吗 ? 谢谢 Esoni

0 个答案:

没有答案