Failed error during websocket handshake unexpected response code 502

I'm using node,socket.io,nginx for socket connections for a http based simple application. below is my nginx.conf where i configured the websockets, my socket io is present in socket/socket.io. Str...

I’m using node,socket.io,nginx for socket connections for a http based simple application. below is my nginx.conf where i configured the websockets, my socket io is present in socket/socket.io. Strange thing is that the same config works perfectly when I run the node application in localhost and nginx with port 80. Not sure why it is failing in linux which real IP addresses.

http {
  upstream io_nodes {
    ip_hash;
    server IP:PORT; --> My application's IP and port
    server IP:PORT;

  }

  include mime.types;
  default_type application/octet-stream;
  sendfile on;
  keepalive_timeout 1000;

  # HTTP Server
  server {
    listen 80;
    server_name IP;
    server_tokens off;
    #proxy_ssl_verify off;

    # prevents 502 bad gateway error
    large_client_header_buffers 8 32k;

    location /dummy/ {
      root html;
      index dummy/index.html;
    }

    location /socket/socket.io {
    proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

      # prevents 502 bad gateway error
        proxy_buffers 8 32k;
        proxy_buffer_size 64k;

      proxy_pass http://io_nodes/;
      proxy_redirect off;

      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;
    }

    #location /socket.io/ {
    #  proxy_pass http://io_nodes/socket.io/;
    #}

    location /assistlog/socket.io {
    proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

    # prevents 502 bad gateway error
        proxy_buffers 8 32k;
        proxy_buffer_size 64k;

      proxy_pass http://10.73.52.187:4444/;
      proxy_redirect off;

      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";

      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;

    }
}
}

and this is the console error in chrome

WebSocket connection to 'ws://IP/socket/socket.io/?pathName=%2FDEMOUI%2Findex.html&EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 502

Please suggest a solution.

asked Aug 20, 2017 at 4:34

Santosh Ksl's user avatar

Santosh KslSantosh Ksl

1622 silver badges8 bronze badges

3

Check list:
First check whether your browser is supporting web sockets using https://websocket.org/echo.html

Then, if you are under organisation proxy, then you need to by pass proxy for local addresses.

Let us say, your organisation proxy IP is some x.x.x.x. You need to by pass some addresses(from the application where you need wss/ws connecctions) to NOT to use your org proxy.

Example in Mac, Chrome: Settings, search for proxy, and there you can see «bypass proxy settings for these hosts&domains». Add your application IP there

answered Oct 3, 2018 at 6:44

Santosh Ksl's user avatar

Santosh KslSantosh Ksl

1622 silver badges8 bronze badges

Содержание

  1. Error during WebSocket handshake: Unexpected response code: 502 using NodeJS and Express #3612
  2. Comments
  3. Footer
  4. Nginx — ошибка во время рукопожатия WebSocket: неожиданный код ответа: 502

Error during WebSocket handshake: Unexpected response code: 502 using NodeJS and Express #3612

I am using Socket IO (versions mention below) and facing a handshake issue as shown in the below screenshot. Earlier I was getting CORS error and resolved it by adding transports: [‘websocket’]
on the client-side and suddenly this issue got pop up.

Versions I am using:

On Client Side:

On Server Side:

The text was updated successfully, but these errors were encountered:

Try on Back-end:
`const express = require(‘express’);
const app = express();
const portSocketIO = process.env.PORT ||5000;
const server = require(‘http’).createServer(app).listen(portSocketIO);

Try on Front-end:

const socket = socketIOClient(endpoint, < query: < socketId: personId >>); socket.on(‘connect’, () => console.log(«I’m logged»));

Depending on your setup not all transport protocols will run properly.
In your case your client specify websocket only with the following line
transports: [‘websocket’]

You can either remove that line or specify both websocket with polling the following way
transports: [‘websocket’, ‘polling’]

They will have the same effect as socket.io estabilishes a long polling connection first then tries to ubpgrade to websocket tries websockets, but the latter will throw the exception (but still works).
In my experience if you know websocket won’t be available just use long polling only
transports’: [‘polling’]

This happens for example when you’re behing a webview or if your server proxy configurations aren’t setup properly or if you don’t have access to those.

Closed due to inactivity, please reopen if needed.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Nginx — ошибка во время рукопожатия WebSocket: неожиданный код ответа: 502

Я запускаю сервер websocket на своей капле Digital Ocean, используя pm2. Кроме того, я использую библиотеку websocket / ws websocket.

Он прослушивает порт 3030.

Используя команду, netstat -l -p я могу увидеть, что он действительно слушает.

Ниже приведена настройка моего файла конфигурации с поддержкой сайтов nginx. Я запускаю статические файлы по / URL-адресу и использую /socket URL-адрес. И / path / to / blah изменен по соображениям безопасности.

При подключении к веб-сокету с помощью wss://www.xxxx.com/socket . Я получаю такую ​​ошибку:

Error during WebSocket handshake: Unexpected response code: 502

Глядя на файл журнала для Nginx, расположенный по адресу /var/log/nginx . Это ошибка, которую я вижу.

[error] 31009#31009: *19 upstream prematurely closed connection while reading response header from upstream, client: X.X.XX.XXX, server: xxxxx.com, request: «GET /socket HTTP/1.1», upstream: «http://127.0.0.1:3030/socket», host: «www.xxxxx.com»

При проверке заголовка для этого веб-сокета. Вот что у меня получилось.

Источник

User267652828 posted

When trying to establish a web socket connection using SignalR I get an unexpected response error 502.

IE 10 reports: ‘WebSocket Error: Incorrect HTTP response. Status code 502, Bad Gateway’

Chrome reports: ‘WebSocket connection to ‘wss://domain/root/signalr/connect?transport=webSockets&client….’ failed: Error during WebSocket handshake: Unexpected response code: 502′

….and after this SignalR then falls back to another transport — so everything still works, but i really want to get this working using web sockets.

When I connect directly to the server, everything works as it should.

I have spend about 3-4 days now searching for how to get SignalR 2.2.1 working with an IIS 8.5, in Windows
Server 2012 R2, ARR 3.0.

I am using SSL/https — I have sticky sessions configured, same machine key on all my back end servers.

I have setup a test system, that has only a single server behind a single ARR load balancer, I have tried every suggestion that I can find but I still cant find a solution — or for that matter anyone indicating that they have successfully configured this
even though Microsoft claim it is support «with no extra config».

Can anyone point me towards a guide or reference for getting this working ?

What other steps should I be trying to debug this configuration ?

Can anyone confirm it even works — or even that it does not work ?

I asked on stackoverflow but so far haven’t had even a single response after a week — I really like ARR & URL Rewrite, I have used it for quite a few years now with millions of requests a day going through it, but with the lack of any documentation or
assistance for ARR in general I am having to seriously consider finding another solution ….

https://stackoverflow.com/questions/44092063/signalr-websocket-fails-with-unexpected-response-code-502-iis-8-5-arr-3-0

If anyone can actually help me get this working I will take the time to write some documentation on how to make it work — step by step, with all the source code for a test SignalR app, all the configuration for IIS, ARR, UrlRewrite — and post it all
on github, microsoft docs or somewhere that others can find !

 

Пользователь 936775

Посетитель

Сообщений: 72
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 08.02.2017

Доброго времени суток. После смены IP отвалился Push and Pull.
Смотрел эту тему:

https://dev.1c-bitrix.ru/support/forum/forum32/topic98131/?PAGEN_1=2

Решения не обнаружил. Используется VM 7.3 Как мне его запустить?

 

Пользователь 936775

Посетитель

Сообщений: 72
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 08.02.2017

 

Пользователь 936775

Посетитель

Сообщений: 72
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 08.02.2017

Нашел ошибку!

$check = new CSiteCheckerTest();
$check->check_socket_ssl();

Connection to ssl://localhost:443 (certificate check enabled)    Fail Connection to ssl://localhost:443    Fail Нравится16:23

Очевидно из-за этого не пашит. В чём причина может быть?

 

Пользователь 936775

Посетитель

Сообщений: 72
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 08.02.2017

#4

0

14.09.2018 13:45:48

Обновил VM до версии 7.3.2.
Теперь в консоле:

Код
PULL notice: script is already loaded kernel_im_v1.js?15349719881571745:46098
(anonymous) @ kernel_im_v1.js?15349719881571745:46098
(anonymous) @ kernel_im_v1.js?15349719881571745:47561
pull.js?152282313141914:415 WebSocket connection to 'wss://sitename/bitrix/subws/?CHANNEL_ID=7f98fe340306595585c7b6f3288f7db9.906209b2b693ae212533addcbcbe7371b324501c/163a216a4bc17587629be49137b4c6ca.f292d69e8531147ea076e6f09f8300541dfbd1dc&tag=1&time=Fri,%2018%20Mar%202022%2021:00:00%20GMT' failed: Error during WebSocket handshake: Unexpected response code: 502
BX.PULL.connectWebSocket @ pull.js?152282313141914:415
BX.PULL.updateState @ pull.js?152282313141914:400
BX.PULL.init @ pull.js?152282313141914:187
BX.PULL.start @ pull.js?152282313141914:182
(anonymous) @ (index):2887
runReady @ kernel_main_v1.js?1536918839575941:5286
__readyHandler @ kernel_main_v1.js?1536918839575941:5223

Так же не пропали ошибки при проверке системы.
С ресурсами порядок.

Код
WebSocket connection to 'wss://crm.dsmed.ru/bitrix/subws/?CHANNEL_ID=7f98fe340306595585c7b6f3288f7db9.906209b2b693ae212533addcbcbe7371b324501c/163a216a4bc17587629be49137b4c6ca.f292d69e8531147ea076e6f09f8300541dfbd1dc&tag=1&time=Fri,%2018%20Mar%202022%2021:00:00%20GMT' failed: WebSocket opening handshake timed out

Прикрепленные файлы

Снимок экрана от 2018-09-14 14-24-38.png (44.98 КБ)

Снимок экрана от 2018-09-14 14-32-41.png (2.58 КБ)

 

Пользователь 936775

Посетитель

Сообщений: 72
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 08.02.2017

Ситуация с проблемой! При смене место положения нашего сервера поменялся IP.
1. Необходимо исправить в файле hosts на новый IP.
2. Баг VM Bitrix. В ней так же необходимо исправить IP.  Но на момент написания данного комментария исправить это в VM нельзя. Я имею в виду NetAddress. Служба поддержки вроде работает над ним.

Может кто подскажет где мне его в файлах VM поменять?

И где VM правит фай push-server-multi?

Список файлов в которых встречается мой IP:
/etc/ansible/hosts // Формируется VM Bitrix
/etc/ansible/group_vars/bitrix-hosts.yml
/etc/ansible/ansible-roles
/etc/munin/munin-node.conf
/etc/munin/conf.d/munin-hosts.conf
/etc/nagios/nrpe.cfg
/etc/nagios/bitrix-pool/crm.cfg
/etc/sysconfig/push-server-multi
/etc/firewalld/zones/bx_trusted.xml
/etc/.hg/store/data/ansible/hosts.i
/etc/.hg/store/data/munin/conf.d.hg/munin-hosts.conf.i

Внимание вопрос: какие формируются VM Bitrix а с каких подтягивает инфу?

 

Пользователь 936775

Посетитель

Сообщений: 72
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 08.02.2017

К сожалению, смена IP в файлах ни к чему не привела( Странно почему. И тут поспел ответ тех. поддержки и они говорят переустановить VM Bitrix.

 

Пользователь 936775

Посетитель

Сообщений: 72
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 08.02.2017

#7

0

20.09.2018 14:40:40

Обновился до бэтки. Дальше очень интересно себя всё повело! При авторизации пользователя в системе сначала сверху выскакивает синее окно с надписью «Соединение установлено» потом через пару секунд — желтое с надписью «Ожидает соединения»  такая игра фраз повторяется три раза потом окончательно висит надпись на красном фоне, что «нет соединения с сервером».

Ошибки в консоле:

Код
PULL notice: script is already loaded
Failed to load resource: the server responded with a status of 400 ()
 

Пользователь 936775

Посетитель

Сообщений: 72
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 08.02.2017

Долго я уже мучаюсь. Установил заново VM и вы думаете всё поехало? Нет! Виртуальная машина настраивает конфиги не совсем верно. Она создаёт фай /etc/hosts  c внутренним IP. В итоге у меня горела табличка вверху экрана, что нет соединения с сервером. Я залез и изменил там IP на внешний ( перед машиной стоит роутер, указал его IP). Теперь p&p не рыба ни мясо. То работает то не работает) Т.е. через секунд 40 он обновляется. И в логи валится ошибка сокета 400. Почему это так работает?

Моя логика подсказывает: У нас есть пул и у него должен быть внешний IP а у сайтов в пуле локальные. Так?

 

Пользователь 936775

Посетитель

Сообщений: 72
Баллов: 5
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 08.02.2017

#9

0

02.10.2018 14:46:02

Частично проблему решил. Найден БАГ! Непонятно где он в коробке или VM, но при развороте бекапа сайта (коробки) с переустановленным окружением не прописывается «Код-подпись для взаимодействия с сервером» в настройках модуля Push and Pull. В результате не работал НИКАКОЙ P&P!!! Достать этот ключ получилось методом установки на новый сайт демонстрационной версии коробки и там в настройках его копировать. Кроме того после разворота отваливаются сокеты и модули. Пока не знаю как восстановить их работу.

Заработал модуль Push/RTC service, но не NGINX.

870 votes

1 answers

Get the solution ↓↓↓

Has anybody successfully gotten the php ratchet library working with NGINX using WSS. Am really struggling with it. I have the ratchet server running on port 8081. I can confirm that the socket server is listening on port 8081 and I can connect no problem using the ws protocol with no issue.

var conn = new WebSocket('ws://connect.mydomain.net:8081');

Now to configure WSS andhave NGINX to proxy to this I have the following NGINX configuration


    map $http_upgrade $connection_upgrade {
        default Upgrade;
        '' close;
    }

    upstream socket{
        server localhost:8081;
        #server connect.mydomain.net:8081;
    } 

    location /ws/ {
            #proxy_pass "http://socket";
            proxy_pass "https://connect.mydomain.net:8081";
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_set_header Host $host;
            proxy_redirect off;
            proxy_send_timeout 86400s;
            keepalive_timeout 86400s;
            proxy_buffers 8 32k;
            proxy_buffer_size 64k;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto https;
            reset_timedout_connection on;
        }

Yet when I try to connect using

var conn = new WebSocket('wss://connect.mydomain.net/ws/');

I get failed: Error during WebSocket handshake: Unexpected response code: 502

Can anyone please direct highlight anything I may be doing wrong?

Thanks

2021-11-16

Write your answer


822

votes

Answer

Solution:

In my case the issue was SELinux not allowing outbound connections

Running the following fixed my issue…

setsebool -P httpd_can_network_connect 1

Seems like an obvious thing that all docs an similar issues on her seem to omit


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-11-16

Link To Source

Link To Answer
People are also looking for solutions of the problem: call to undefined function str_contains()

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Понравилась статья? Поделить с друзьями:
  • Failed error during websocket handshake unexpected response code 301
  • Failed error during websocket handshake unexpected response code 200
  • Failed error caused by file vmfs volumes
  • Failed error 0xc004f074 при активации kmsauto
  • Failed error 0xc004f074 kmsauto windows 10