SpringWebSocket服务器和react客户端
我必须用spring开发一个web套接字服务器,它每5秒向客户端发送一条消息。客户端是用react js编写的。这是我的服务器代码:SpringWebSocket服务器和react客户端,spring,spring-boot,spring-websocket,sockjs,spring-web,Spring,Spring Boot,Spring Websocket,Sockjs,Spring Web,我必须用spring开发一个web套接字服务器,它每5秒向客户端发送一条消息。客户端是用react js编写的。这是我的服务器代码: @SpringBootApplication @EnableAsync @EnableScheduling public class TestwsApplication { public static void main(String[] args) { SpringApplication.run(TestwsApplication.cl
@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');
};
}
在日志上我只看到post open套接字。。。我没有在onmessage中看到任何日志。。。因此,客户端没有收到消息。为什么?你能帮助我吗?
谢谢
Esoni您的计划程序和服务类恰好有相同的代码。请尽快更新。。我现在已经更新了你解决了这个问题吗??我在同一个环境(SpringBoot+React)中遇到了类似的问题,您的调度程序和服务类恰好有相同的代码。请尽快更新。。我现在已经更新了你解决了这个问题吗??我在相同的环境中遇到了类似的问题(Spring Boot+React)