2017-08-12 350 views
3

在连接反应基于WebSocket的客户端基于Java的Web码头套接字服务器,我收到以下错误 -错误:意外响应代码:302

WebSocket connection to 'ws://localhost:2319/ws' failed: Error during WebSocket handshake: Unexpected response code: 302 

这不存在错误,同时连接通过Chrome的智能网络套接字客户端。

我正在尝试开发基于REACT的Web Socket客户端。客户端代码是 -

var connection = new WebSocket('ws://localhost:2319/ws'); 
    connection.onopen = function() { 
    // connection is opened and ready to use 
    }; 

WebSocket服务器基于Jetty。服务器代码 -

server = new Server(); 
    ServerConnector connector = new ServerConnector(server); 
    connector.setPort(SSConstants.WWBSOCKET_PORT); 
    server.addConnector(connector); 

    // Setup the basic application "context" for this application at "/" 
    // This is also known as the handler tree (in jetty speak) 
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); 
    context.setContextPath("/ws"); // Set to "/ws" for future integration with the main jetty server. 
    server.setHandler(context); 

    try { 
     // Initialize javax.websocket layer 
     ServerContainer wsContainer = WebSocketServerContainerInitializer.configureContext(context); 

     // Add WebSocket endpoint to javax.websocket layer 
     wsContainer.addEndpoint(WebsocketListener.class); 
     server.start();   
    } 
    catch (Throwable t) { 
     ssLogger.logInfo("Websocket Server start exp : "); 
     t.printStackTrace(System.err); 
    } 

输出 -

WebSocket connection to 'ws://localhost:2319/ws' failed: Error during WebSocket handshake: Unexpected response code: 302 

Request URL:ws://localhost:2319/ws 
Request Method:GET 
Status Code:302 Found 

Response Headers 
view source 
Content-Length:0 
Date:Fri, 11 Aug 2017 18:51:42 GMT 
Location:http://localhost:2319/ws/ 
Server:Jetty(9.3.8.v20160314) 

Request Headers 
view source 
Accept-Encoding:gzip, deflate, br 
Accept-Language:en-US,en;q=0.8 
Cache-Control:no-cache 
Connection:Upgrade 
Host:localhost:2319 
Origin:https://localhost:1338 
Pragma:no-cache 
Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits 
Sec-WebSocket-Key:2OZooIjOX7G6kgNpPOz9Fw== 
Sec-WebSocket-Version:13 
Upgrade:websocket 
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36 
Name 

回答

4

ws://localhost:2319/ws不是有效的端点URL/URI,它要重定向到正确的为您宣布contextPath/ws

那是什么302重定向告诉你...

Location: http://localhost:2319/ws/

比方说你WebsocketListener被声明为@ServerEndpoint("/ws"),我们使用您的ServletContext"/ws"contextPath这将意味着你的URL/URI访问的WebSocket端点...

ws://localhost:2319/ws/ws

还是在说不同的方式...

ws://<host>:<port>/<contextPath>/<endpointPath>

+0

Thanks for this。让我意识到我使用了错误的位置.. – Lagoni

相关问题