【问题标题】:How to get websocket response on server with spring+stomp+sockjs?如何使用 spring+stomp+sockjs 在服务器上获取 websocket 响应?
【发布时间】: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


    【解决方案1】:

    看到你的代码有几个误区:

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

    查看Spring WebSocket Chat application

    【讨论】:

    • 非常感谢您的回答,我在上面进行了编辑,但是当我尝试连接时,在浏览器控制台中出现下一条消息:WebSocket connection to 'ws://localhost:8080/hello ' 失败:WebSocket 握手期间出错:意外响应代码:200
    猜你喜欢
    • 1970-01-01
    • 2017-05-27
    • 2017-09-17
    • 2017-06-05
    • 2016-06-18
    • 2016-11-09
    • 2016-07-04
    • 1970-01-01
    • 2017-10-04
    相关资源
    最近更新 更多