【发布时间】:2015-04-02 02:41:20
【问题描述】:
在我的 javascript 中,我创建了一个 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>
我还有一个简单的表单(名称 testWebSocket.jsp),带有按钮和下一个功能:
// function to send message
function fnSayHi() {
stompClient.send("/hello", JSON.stringify({ 'name': 'Joe' }));
}
....
<input onclick="fnSayHi();" type="button">
当我单击视图中的按钮时,在控制台浏览器中我们看到发送数据,(您可能会在图像上看到)并且我想获取发送的数据 websocket 并将它们显示在服务器控制台中(如 System.out.println( ..))?谢谢!
控制器:
@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 + "!");
}
}
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>
【问题讨论】:
标签: spring-mvc controller websocket stomp sockjs