While connecting to REACT based WebSocket client to Java Jetty based Web Socket server, I am getting the error below —
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.
I am trying to develop Web Socket Client based on REACT. Client code is —
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 —
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
Hi Peter,
I extensively investigated the problem. I logged incoming connections to total.js and noticed wesocket connections have no upgrade
command in this situation. e.g:
headers:
{ host: 'staging.nikoo.ir',
pragma: 'no-cache',
origin: 'http://staging.nikoo.ir',
'sec-websocket-version': '13',
'user-agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
'accept-encoding': 'gzip, deflate, sdch',
'accept-language': 'en-US,en;q=0.8,fa;q=0.6',
cookie: '__ssid=OTc9QU4CT0wNHE1cW0NKcVlMAQocHk0GDVwbW1cPZm9kLDQ8MGtGEVQfVwcEAkltSVJGSgNOBx8eDBIYSE5ETA0OGx9KHhEjOWw4aD8oZD1ARw; ...',
'sec-websocket-key': '2plrNNLzVAix5Ww2MBVWkg==',
'sec-websocket-extensions': 'permessage-deflate; client_max_window_bits',
'cache-control': 'no-cache, max-age=0',
connection: 'keep-alive' }
it is the expected headers (a working example):
headers:
{ host: 'staging.nikoo.ir',
connection: 'Upgrade',
pragma: 'no-cache',
'cache-control': 'no-cache',
upgrade: 'websocket',
origin: 'http://staging.nikoo.ir',
'sec-websocket-version': '13',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36',
'accept-encoding': 'gzip, deflate, sdch',
'accept-language': 'en-US,en;q=0.8,fa;q=0.6',
cookie: '__ssid=OTc9QU4CT0wNHE1cW0NKcQoaBFkZSUpXDwgbW1cPZm9kLDQ8Yz1DQlFIUFYGVkltSVJGSgNOBx8eDBIYSE5ETA0OGx9KHhEjajo9Ozp-Y2xCEw;...',
'sec-websocket-key': 'voIySAu7w3K4wloc288Gfg==',
'sec-websocket-extensions': 'permessage-deflate; client_max_window_bits' }
So the faulty request is the culprit and I can say for sure that it has nothing to do with total.js
.
I checked websocket connections from my computer to another tested server (http://www.websocket.org/echo.html) and found them to be broken too. I don’t know if it is my ISP or a third-party application (antivirus, etc) on my computers which causes the problem. I’ll check it out further and post the result here when I cornered the issue.
Fadjr 1 / 1 / 1 Регистрация: 28.09.2015 Сообщений: 129 |
||||
1 |
||||
20.01.2016, 20:44. Показов 2032. Ответов 2 Метки нет (Все метки)
WebSocket connection to ‘ws://steamcommunity.com/login/home/?goto=%2Ftradeoffer%2Fnew%2F%3Fpartner%3DURL:8305’ failed: Error during WebSocket handshake: Unexpected response code: 302. в чём ошибка?……или сайт на котором зарегистрирован домен не поддерживается? P.S я хочу добавить ссылку на сайт которая бы подключилась к стиму….ну или хотя бы к сайту без проблем…… это стока которая ему не нравится
__________________
0 |
413 / 378 / 220 Регистрация: 18.07.2014 Сообщений: 1,259 |
|
21.01.2016, 12:49 |
2 |
Fadjr, 302 код ответа говорит о том что запрошенный ресурс перенесен на другой адрес
0 |
1 / 1 / 1 Регистрация: 28.09.2015 Сообщений: 129 |
|
25.01.2016, 09:28 [ТС] |
3 |
как решить эту проблему если я не знаю по какому адресу находится новый ресурс…….может…………..присвоить….имя разрабатываемого сайта? после регистрации домена?
0 |
I’m unable to make websockets work on a node backend using an apache proxy through HTTPS to connect to the node instance. Websockets are working properly if no (apache) http(s) proxy is used.
My setup: I have an apache server with multiple virtual hosts. I have a HTTPS webpage for myserver.com and the HTTPS API with node/express/ws in api.myserver.com subdomain through the proxy, that redirects the requests to the node.js instance (multiple instances on PM2) running on port 3333.
This is my apache virtual host for the subdomain:
<VirtualHost *:443>
ServerName api.myserver.com
ServerAdmin hello@myserver.com
DocumentRoot /var/www/html/myserver/api
Options -Indexes
SSLEngine on
SSLProtocol all -SSLv2
SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM
SSLCertificateFile /etc/apache2/certs/STAR_myserver_co.crt
SSLCertificateKeyFile /etc/apache2/certs/myserver_private_key.pem
SSLCertificateChainFile /etc/apache2/certs/STAR_myserver_co.ca-bundle
SSLProxyEngine On
ProxyPreserveHost On
ProxyRequests Off
# This is for websocket requests
ProxyPass /wss/ wss://localhost:3333/
ProxyPassReverse /wss/ wss://localhost:3333/
# This is for normal requests
ProxyPass / https://localhost:3333/
ProxyPassReverse / https://localhost:3333/
</VirtualHost>
This works OK for redirecting the connections to the node express backend. I have installed mod_proxy, mod_proxy_http and mod_proxy_wstunnel.
This is the node.js API backend: first, I initialize express, sessions, etc.
// express, session and mongodb session storage
var express = require('express')
var session = require('express-session')
var MongoStore = require('connect-mongo')(session)
var app = express()
// configure sessionStore and sessions, mongodb, etc...
// Certificates and credentials for HTTPS server
var fs = require('fs')
var privateKey = fs.readFileSync(__dirname + '/certs/myserver_private_key.pem', 'utf8')
var certificate = fs.readFileSync(__dirname + '/certs/myserver_cert.pem', 'utf8')
var ca = fs.readFileSync(__dirname + '/certs/myserver_ca.pem', 'utf8')
var credentials = {key: privateKey, cert: certificate, ca: ca}
app.enable('trust proxy')
app.set("trust proxy", 1)
And then I setup the HTTPS server securely, using the same certificates that in APACHE:
// Setup HTTPS server
var https = require('https')
var server = https.createServer(credentials, app)
server.listen(appPort, 'localhost', function () {
// Server up and running!
var host = server.address().address
var port = server.address().port
console.log('myserver listening at https://%s:%s', host, port)
})
Last, I setup the websocket connections:
// setup Websockets
wss = new WebSocketServer({ server: server })
wss.on('connection', function connection(ws) {
var cookies = cookie.parse(ws.upgradeReq.headers.cookie)
var sid = cookieParser.signedCookie(cookies["connect.sid"], myserver_secret)
// extract user credentials and data from cookie/sid,
// get the session object
sessionStore.get(sid, function (err, ss) {
...
})
})
Then my clients just try to connect to websockets securely (because, being a HTTPS app, I cannot use the ws:// insecure websockets connection):
window.WebSocket = window.WebSocket || window.MozWebSocket
webSocket = new WebSocket('wss://' + location.host + '/wss')
And then I get always the same error 302:
[Error] WebSocket connection to 'wss://api.myserver.com/wss' failed: Unexpected response code: 302
If I test on a local server directly to the node instance https://localhost:3333/ it’s working perfectly and websockets work as they should.
Any idea of how to solve this? Is there a problem with ws redirections made by Apache proxy modules?
While connecting to REACT based WebSocket client to Java Jetty based Web Socket server, I am getting the error below —
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.
I am trying to develop Web Socket Client based on REACT. Client code is —
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 —
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