spring整合websocket出错,Unexpected response code: 404

  1. 下面是代码:
    public class MarcoHandler extends AbstractWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    System.out.println("Received message:"+message.getPayload());
    Thread.sleep(2000);
    session.sendMessage(new TextMessage("Polo!"));
    }

}
websocket的xml配置

<websocket:handlers>
    <websocket:mapping handler="marcoHandler" path="/marco"/>
</websocket:handlers>
<bean id="marcoHandler" class="com.camle.entity.MarcoHandler"/>

web.xml的配置


  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:websocket.xml</param-value>
    </context-param>

javascript代码

var url = 'ws://'+window.location.host+'/mvcAndWebsocket/marco'; var sock = new WebSocket(url); sock.onopen = function(){ console.log('Opening'); sayMarco(); }; sock.onmessage = function(e){ console.log('Received message:',e.data); setTimeout(function(){sayMarco()},2000); }; sock.onclose = function(){ alert(window.location.host); console.log('Closing'); }; function sayMarco(){ console.log('Sending Marco!'); sock.send('Marco!'); }

https://github.com/jelly-liu/spring-websocket,现成的例子,直接使用

参考:

[Error during WebSocket handshake: Unexpected response code: 404错误的解决](https://blog.csdn.net/clever101/article/details/97617044 "")