Add websocket example
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
package org.baeldung.model;
|
||||
|
||||
public class Message {
|
||||
|
||||
private String text;
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.baeldung.model;
|
||||
|
||||
public class OutputMessage {
|
||||
|
||||
private String text;
|
||||
private String time;
|
||||
|
||||
public OutputMessage(final String text, final String time) {
|
||||
this.text = text;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public String getTime() {
|
||||
return time;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.baeldung.spring.web.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(final MessageBrokerRegistry config) {
|
||||
config.enableSimpleBroker("/topic");
|
||||
config.setApplicationDestinationPrefixes("/app");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerStompEndpoints(final StompEndpointRegistry registry) {
|
||||
registry.addEndpoint("/chat").withSockJS();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package org.baeldung.web.controller;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.baeldung.model.Message;
|
||||
import org.baeldung.model.OutputMessage;
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.SendTo;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
@Controller
|
||||
public class ChatController {
|
||||
|
||||
@RequestMapping(value = "/showChat", method = RequestMethod.GET)
|
||||
public String displayChat() {
|
||||
return "chat";
|
||||
}
|
||||
|
||||
@MessageMapping("/chat")
|
||||
@SendTo("/topic/")
|
||||
public OutputMessage send(final Message message) throws Exception {
|
||||
|
||||
final String time = new SimpleDateFormat("HH:mm").format(new Date());
|
||||
return new OutputMessage(message.getText(), time);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user