如何使用spring + stomp + sockjs在服务器上获取websocket响应?

时间:2015-02-03 01:20:22

标签: spring-mvc controller websocket stomp sockjs

在我的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>

enter image description here

1 个答案:

答案 0 :(得分:3)

看到你的代码存在一些误解:

  1. 在您的第一个JS中,当您订阅目的地时, destination不是URL而是目标名称。代替 http://localhost:8080/topic/greetings您应该订阅 /topic/greetings
  2. 在您的第二个JS(testWebSocket.jsp)中,您正在向其发送消息 /hello但是没有这种目的地的映射,你应该这样做 将其发送到/app/hello,而不是/app配置为申请 目的地(这些消息将由您的控制器处理)。
  3. 在您的上一张图片(控制台)中,显示连接丢失, 您的连接网址可能有误http://localhost:8080/hello (可能缺少应用程序名称或servlet映射?)。
  4. 检查Spring WebSocket Chat application