java WebSocket 握手期间出错:意外响应代码:302

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45655753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:49:22  来源:igfitidea点击:

Error during WebSocket handshake: Unexpected response code: 302

javajsonreactjswebsocketjetty

提问by vivek agarwal

While connecting to REACT based WebSocket client to Java Jetty based Web Socket server, I am getting the error below -

将基于 REACT 的 WebSocket 客户端连接到基于 Java Jetty 的 Web Socket 服务器时,出现以下错误 -

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

This error doesn't exist while connecting through Chrome's Smart Web Socket client.

通过 Chrome 的 Smart Web Socket 客户端连接时不存在此错误。

I am trying to develop Web Socket Client based on REACT. Client code is -

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

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

WebSocket Server has been based on Jetty. Server code is -

WebSocket Server 一直基于 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);
    }

Output -

输出 -

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

回答by Joakim Erdfelt

ws://localhost:2319/wsis not the valid endpoint URL/URI, it wants to redirect to the correct one for your declared contextPathof /ws

ws://localhost:2319/ws不是有效的端点 URL/URI,它想重定向到您声明contextPath的正确的/ws

That's what the 302 redirect is telling you ...

这就是 302 重定向告诉你的......

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

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

Lets say your WebsocketListeneris declared as @ServerEndpoint("/ws"), and we use your ServletContextat contextPathof "/ws"that would mean your URL/URI to access that websocket endpoint is ...

比方说,你WebsocketListener是为宣布@ServerEndpoint("/ws"),我们使用您ServletContextcontextPath"/ws",这将意味着你的URL / URI访问的WebSocket端点...

ws://localhost:2319/ws/ws

ws://localhost:2319/ws/ws

Or said in a different way ...

或者换种说法...

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

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

回答by pytData

I recently faced the same issue and this is how I was able to resolve mine.

我最近遇到了同样的问题,这就是我如何解决我的问题。

I changed the port number for my websocket server from 8080 to 8335 which was the same is the same port for my Apache server.

我将 websocket 服务器的端口号从 8080 更改为 8335,这与我的 Apache 服务器的端口号相同。

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;

require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ),
    8335
);

$server->run();

And also made the same changes in my javascript code for the actual connection

并在我的 javascript 代码中对实际连接进行了相同的更改

let conn = new WebSocket('ws://localhost:8335');
conn.onopen = function(e) {
    console.log("Connection established!");

    conn.send('Hello Everyone');
};

conn.onmessage = function(e) {
    console.log(e.data);
    $("#msg").append('<br>'+e.data);
};

You can also lookup for free ports in the Apache controller by following the images below. Thanks

您还可以按照下图在 Apache 控制器中查找空闲端口。谢谢

click on Netstart on the Xampp Controller

单击 Xampp 控制器上的 Netstart

enter image description here

在此处输入图片说明

Click to refresh to view Active Socket, New Sockets and Old Sockets

点击刷新查看活动套接字、新套接字和旧套接字

Select any of the ports that falls in the burgundy section

选择属于勃艮第部分的任何端口

Thank you

谢谢