I’ve recently started to work with websockets and I’m not sure what is the best approach for what I need.
For backend I’m using spring boot/java and frontend react/typescript. What I need is to have button start counting and when user click on the button it will trigger function on the backend to start counting from 1 to 10 and it will send frontend updates(multiple messages) regarding counting. Under the button on frontend there will be Counting: {count} to let user know what is the status.
Thanks for any advices.
const WebSocketComponent: React.FC = () => {
const [count, setCount] = useState<number>(0);
const [client, setClient] = useState<Client | null>(null)
const jwtToken = useStore((state: any) => state.jwtToken)
useEffect(() => {
const stompClient = new Client({
brokerURL: 'ws://localhost:8310/webrde/ws', // Replace with your WebSocket endpoint
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
onConnect: () => {
console.log('Connected to WebSocket server');
stompClient.subscribe('/user/queue/update', (message: any) => {
const { count } = JSON.parse(message.body);
setCount(count);
});
console.log(count)
},
onDisconnect: () => {
console.log('Disconnected from WebSocket server');
},
});
stompClient.activate();
setClient(stompClient);
return () => {
stompClient.deactivate();
};
}, []);
const handleButtonClick = () => {
if (client) {
client.publish({
destination: `/webrde/start-counting/${jwtToken}`,
});
}
};
return (
<div>
<button onClick={handleButtonClick}>Start Counting</button>
<p>Counting: {count}</p>
</div>
);
};
export default WebSocketComponent;
@Controller
public class WebSocketController {
private final SimpMessagingTemplate messagingTemplate;
public WebSocketController(SimpMessagingTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
@MessageMapping("/start-counting/{userId}")
@SendToUser(value = "/queue/update", broadcast = false)
public void startCounting(@DestinationVariable String userId) {
System.out.println("Start counting...");
for (int i = 1; i <= 10; i++) {
String message = "{"count": " + i + "}";
System.out.println("Sending message: " + message);
messagingTemplate.convertAndSendToUser(userId, "/queue/update", message);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Counting completed.");
}
}
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue", "/topic");
registry.setApplicationDestinationPrefixes("/webrde");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("http://localhost:3011");
}
}
cutie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.