Por 9.99€ al mes tendrás acceso completo a todos los cursos. Sin matrícula ni permanencia.
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
Cuando una petición llegue a un endpoint que comience por app, será procesado utilizando sockets.
com.pablomonteserin.prueba.WebSocketConfig
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket");
}
}
com.pablomonteserin.prueba.GreetingController.java
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
}
com.pablomonteserin.prueba.Greeting.java
@Getter
public class Greeting {
private String content;
public Greeting(String content) {
this.content = content;
}
}
com.pablomonteserin.prueba.HelloMessage.java
@Getter @Setter
public class HelloMessage {
private String name;
}
El Cliente
<style>
.status {
width: 50px;
height: 50px;
border-radius: 100%;
background-color: red;
}
</style>
<div class="status"></div>
<button onClick="connect()">Connect</button>
<button onClick="sendName()">Send</button>
<div id="conversation"></div>
<script src="https://cdn.jsdelivr.net/npm/@stomp/stompjs@7.0.0/bundles/stomp.umd.min.js"></script>
<script>
const stompClient = new StompJs.Client({
brokerURL: "ws://localhost:8080/gs-guide-websocket",
});
stompClient.onConnect = (frame) => {
console.log("Connected: " + frame);
stompClient.subscribe("/topic/greetings", (greeting) => { document.querySelector('#conversation').innerHTML+='<p>'+JSON.parse(greeting.body).content+'</p>';
});
};
stompClient.onWebSocketError = (error) => {
console.error("Error with websocket", error);
};
stompClient.onStompError = (frame) => {
console.error("Broker reported error: " + frame.headers["message"]);
console.error("Additional details: " + frame.body);
};
const status = document.querySelector(".status");
function connect() {
stompClient.activate();
status.style.backgroundColor = "green";
}
function disconnect() {
stompClient.deactivate();
status.style.backgroundColor = "red";
}
function sendName() {
stompClient.publish({
destination: "/app/hello",
body: JSON.stringify({ name: "daniel" }),
});
}
function showGreeting(message) {
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}
</script>
Descargar código