在我的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>
答案 0 :(得分:3)
看到你的代码存在一些误解:
http://localhost:8080/topic/greetings
您应该订阅
/topic/greetings
。testWebSocket.jsp
)中,您正在向其发送消息
/hello
但是没有这种目的地的映射,你应该这样做
将其发送到/app/hello
,而不是/app
配置为申请
目的地(这些消息将由您的控制器处理)。http://localhost:8080/hello
(可能缺少应用程序名称或servlet映射?)。