Reputation: 121
In my javascript I create a websocket:
<script type="text/javascript">
/// Create stomp client over sockJS protocol (see Note 1)
var socket = new SockJS("http://localhost:8080/hello");
var stompClient = Stomp.over(socket);
// callback function to be called when stomp client is connected to server (see Note 2)
var connectCallback = function() {
alert("connected!");
stompClient.subscribe('http://localhost:8080/topic/greetings', function(greeting){
alert(JSON.parse(greeting.body).content);
});
};
// callback function to be called when stomp client could not connect to server (see Note 3)
var errorCallback = function(error) {
// display the error's message header:
alert(error.headers.toString);
};
// Connect as guest (Note 4)
stompClient.connect("guest", "guest", connectCallback, errorCallback);
</script>
And also I have a simple form(name testWebSocket.jsp) with button and next function:
// function to send message
function fnSayHi() {
stompClient.send("/hello", JSON.stringify({ 'name': 'Joe' }));
}
....
<input onclick="fnSayHi();" type="button">
When I click on button in my view, in the console browser we see sending data, (you might see on image) and I want to get sent data websocket and display them in server console(like System.out.println(..))? Thanks.!
Controller:
@Controller
public class MessageController {
@RequestMapping("/test")
public ModelAndView getBodyPage() throws SQLException {
ModelAndView modelAndView = new ModelAndView("testWebSocket");
return modelAndView;
}
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(String name) throws Exception {
System.out.println(name);//here!
return new Greeting("Hello, " + name + "!");
}
}
part of spring-config:
<!-- WebSocket -->
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/hello">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
Upvotes: 0
Views: 3054
Reputation: 8414
There are several misunderstandings seeing your code:
http://localhost:8080/topic/greetings
you should subscribe to
/topic/greetings
.testWebSocket.jsp
), you are sending a message to
/hello
but there's no mapping for such destination, you should
send it to /app/hello
instead as /app
is configured for application
destinations (these messages will be handled by your controllers).http://localhost:8080/hello
(maybe missing the application name or servlet mapping?).Check the Spring WebSocket Chat application
Upvotes: 3