4
Explaining in detail, step-by-step, how to develop the system is something out of scope. But basically you can use Spring Boot to facilitate the hard work.
The architecture is simple:
- The server needs to provide a channel via Websockets so that the client (browser) can receive updates.
- The page must have a Javascript that signs up to receive updates (messages) from the server.
In this tutorial you find a simple example. Above Websockets, it uses a library based on the STOMP protocol for text communication, specifically JSON.
Client
The code in the client to connect, disconnect, send and receive messages is like this:
function connect() {
var socket = new SockJS('/hello');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting){
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
}
The function showGreeting
call in the first method would be responsible for displaying the received message.
Server
You can create a controller to receive and return messages:
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(3000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}
}
Unfortunately, in this example of the tutorial, it just sends a message and ends.
Already in this other tutorial you find an example of how to publish messages in the channel if asynchronous form (at any time):
@Service
public class ScheduleTask {
@Autowired
private SimpMessagingTemplate template;
// this will send a message to an endpoint on which a client can subscribe
@Scheduled(fixedRate = 5000)
public void trigger() {
// sends the message to /topic/message
this.template.convertAndSend("/topic/message", "Date: " + new Date());
}
}
The configuration (according to the second tutorial) is like this:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// the endpoint for websocket connections
registry.addEndpoint("/stomp").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// use the /topic prefix for outgoing WebSocket communication
config.enableSimpleBroker("/topic");
// use the /app prefix for others
config.setApplicationDestinationPrefixes("/app");
}
}
Database
The above examples do not consider databases. Unfortunately, receive database events or do Polling (continuous checking) are generally not possible or even recommended.
Ideally, your system should contain some notification API, where each new message generates a notification that goes to a queue. Eventually some asynchronous code can capture this message and publish to the correct channel, as in the example above where the scheduler publishes the date on the channel.
Of course you can implement this synchronously, but usually it will generate very negative impacts on performance, so real applications don’t do that.
I’m already using spring boot :D thanks for the return :)
– Jose Vieira Neto
This type of implementation is for any kind of data ? for example I have a server and two clients. and customers are players it’s a game, one client "walks" and the other client "see"?
– Jose Vieira Neto
@Josevieiraneto The example implementation transmits information in JSON format. You can adapt the tutorial’s Greeting class to contain any data you want or even transmit in another format. The implementation for a game can use the same principle, where the data structure must transmit the other player’s moves. In that case, I suggest using a different topic per player, so that you can send messages to each one individually. Only if the game is in real time, it will probably be a challenge because you should consider communication latency.
– utluiz
@Josevieiraneto I found an interesting article that tells how a real-time game was made using websockets with a maximum latency of 200 milliseconds: https://cloud.google.com/solutions/real-time-gaming-with-node-js-websocket
– utluiz
Very good article. I appreciate the return.
– Jose Vieira Neto