为什么我在TextWebSocketHandler中无法获得调用函数afterConnectionClosed()?

时间:2016-01-26 15:13:54

标签: spring spring-websocket

在服务器端,我使用Spring-websocket,Handshake如下:

public class WebsocketEndPoint extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session,
            TextMessage message) throws Exception {
        System.out.println("start to translate data!");

        super.handleTextMessage(session, message);
        for (int i = 0; i <= 1000; i++) {
            session.sendMessage(new TextMessage("push message " + i));
            Thread.sleep(2000);
        }
        session.sendMessage(message);
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("Connection Established!");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("Connection Closed!");
    }
}

springmvc.xml如下:

<mvc:default-servlet-handler/>


<bean id="websocket" class="com.yyp.mvc.controller.WebsocketEndPoint" />
<websocket:handlers>
    <websocket:mapping path="/websocket" handler="websocket" />
    <websocket:handshake-interceptors>
        <bean class="com.yyp.mvc.controller.HandshakeInterceptor" />
    </websocket:handshake-interceptors>
</websocket:handlers>

在客户端,我的html如下:

<!DOCTYPE html>

<html>
<head lang="en">
  <meta charset="UTF-8">
</head>
<body>
<button onclick="closeSocket()">stop socket</button>
<script>
  var  wsServer = 'ws://localhost:8080/websocket';
  var  websocket = new WebSocket(wsServer);
  websocket.onopen = function (evt) { onOpen(evt) };
  websocket.onclose = function (evt) { onClose(evt) };
  websocket.onmessage = function (evt) { onMessage(evt) };
  websocket.onerror = function (evt) { onError(evt) };
  function onOpen(evt) {
    console.log("Connected to WebSocket server.");
    websocket.send('hello');
  }
  function onClose(evt) {
    console.log("Disconnected");
  }
  function onMessage(evt) {
    console.log('Retrieved data from server: ' + evt.data);
  }
  function onError(evt) {
    console.log('Error occured: ' + evt.data);
  }
  function closeSocket (argument) {
    console.log("close socket");
    websocket.close();
    websocket=null;
  }
</script>

</body>
</html>

最后,我可以在服务器中获得这样的日志:

before shakeHands
after shakeHands
Connection Established!
start to translate data!

为什么无法获得“连接关闭!”单击“停止套接字”按钮后的日志,或者如何从客户端处理连接关闭信息?

0 个答案:

没有答案