Failed error during websocket handshake unexpected response code 404

Am writing my first websocket program and am getting "WebSocket handshake: Unexpected response code: 404", error while loading the webpage. I am using JDK 1.7 and jboss 8 (wildfly8.0). Could anyone

Am writing my first websocket program and am getting «WebSocket handshake: Unexpected response code: 404», error while loading the webpage.

I am using JDK 1.7 and jboss 8 (wildfly8.0).

Could anyone please assist?

window.onload = init;
var socket = new WebSocket("ws://localhost:8080/WebsocketHome/actions"); 
socket.onmessage = onMessage; 

and head in html

<head> 
 <title></title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <script src="websocket.js" type="text/javascript"></script> 
 <link rel="stylesheet" type="text/css" href="style.css"> 
</head>

Llanilek's user avatar

Llanilek

3,3385 gold badges38 silver badges65 bronze badges

asked Apr 5, 2015 at 9:38

Saurabh Jhunjhunwala's user avatar

1

Actually, the problem here is case-sensitivity in the URLs. You did not need to change the project name. Just changing the Websocket URL in JavaScript file to

ws://localhost:8080/WebSocketHome/actions 

(with capital S, as in the project name) would have solved the problem. In your case, changing both of them removed the case inconsistency, so it worked.

ADyson's user avatar

ADyson

55.2k13 gold badges53 silver badges63 bronze badges

answered Jun 5, 2018 at 12:31

scaleSpace's user avatar

It’s because of the issue of /info=34424 — with 404 error — that I had to abandon using the xml approach suggested at other places. I have Spring 4.2 in my project and many SockJS Stomp implementations usually work well with Spring Boot implementations. This implementation from Baeldung worked(for me without changing from Spring 4.2 to 5). After Using the dependencies mentioned in his blog, it still gave me ClassNotFoundError. I added the below dependency to fix it.

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.2.3.RELEASE</version>
    </dependency>

Baeldung’s implementation curiously does not make any such calls

flow/websocket/add/info?t=1540813753999

What it does (on send and receive) is below. I am only pasting it in case people well-versed with these libraries can further add insights on this forum.

 >>> SEND
destination:/app/chat
content-length:38

{"from":"nicholas","text":"try again"}

<<< MESSAGE
destination:/topic/messages
content-type:application/json;charset=UTF-8
subscription:sub-0
message-id:m3p096zk-11
content-length:53

{"from":"nicholas","text":"try again","time":"13:46"}

answered Sep 30, 2019 at 4:12

veritas's user avatar

veritasveritas

3581 gold badge6 silver badges14 bronze badges

My guess is that you are trying to contact the websocket with a normal browser.
That is not allowed and gives a 404 error. You need to use a script or curl to address websockets.

Christopher Bradshaw's user avatar

answered May 7, 2020 at 14:16

nomail's user avatar

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

alduxvm opened this issue

Mar 2, 2018

· 19 comments

Comments

@alduxvm

I’m using browserify with mqtt, I followed the instructions on the readme file in order to make it…

But when connecting to my broker, I’m getting this error in the console:

WebSocket connection to 'ws://localhost:8083/' failed: Error during WebSocket handshake: Unexpected response code: 404

I tested my broker with other applications using WS and it works… Also, testing mqtt.js without browserify it connects to my broker with no issues. The problem comes when doing the browserify, any idea?

@RangerMauve

I haven’t seen that before, actually.

Could you post a code snippet of how you’re connecting?

@alduxvm

of course… I’m using EMQ as broker, the code I use to connect is:

var mqtt = require('mqtt')
var client  = mqtt.connect({
  host: 'localhost',
  port: 8083,
  username: 'sim',
  password: 'sim',
  clientid: 'test12345'
});

client.on('connect', function () {
  client.subscribe('device/#')
});

client.on('message', function (topic, message) {
  console.log(message.toString())
});

@alduxvm

If I try the connection on the console only (no browser), I can connect changing the port from 8083 to 1883

@RangerMauve

Please note that the browser version only supports the websocket version of MQTT, make sure your broker supports websockets and that you’re using the correct port for websockets.

You also need to set the protocol to ws

@alduxvm

yes, I make sure that my broker works with ws, I tried my broker using this client: http://www.hivemq.com/demos/websocket-client/ and the connection works (I can subscribe and publish)

I added the protocol option but still no luck…

@RangerMauve

Which version of MQTT.js are you using?
You’re sure that 8083 is the correct port to use?
The error message you posted implies that the webserver you’re trying to connect to isn’t listening on WS

@spydmobile

What ever happend to this, I have the exact same issue I have EMQ Broker that works with everything except this lib via websockets, gives the same error as OP.

@RangerMauve

I’m not sure. Are you able to inspect what URLs other libraries are using to connect to the broker? Maybe it’s the trailing / that’s causing a problem.

@alduxvm

Sorry for the delay in replying, my EMQ is 2.3.4 and the MQTT.js is 2.16… I stopped using it due to the error.

@spydmobile

:( ok, what client js mqtt did you switch to?

@spydmobile

ok, I just rewrote using Paho, and it worked, but I would rather work to get mqttjs working…

@RangerMauve

I think this is something we’ll need the EMQ authors to weigh in on.

@spydmobile

@RangerMauve yes quite likely. this lib has no problems connecting to EMQ from the node side, only the browser side.

@tartavull

I’m having a similar problem where nodejs code works correctly but the browser version of the same code doesn’t.

mqtt.js:8236 WebSocket connection to 'wss://mqtt.googleapis.com:8883/' failed: Connection closed before receiving a handshake response

@RangerMauve

@tartavull

@JackGujt

confirm you host name, somethime you can add the string ‘mqtt’ to the end of you host,eg: ‘wxs://xxx.xxxxxxx.xxx/mqtt’

@github-actions

This is an automated message to let you know that this issue has
gone 365 days without any activity. In order to ensure that we work
on issues that still matter, this issue will be closed in 14 days.

If this issue is still important, you can simply comment with a
«bump» to keep it open.

Thank you for your contribution.

@github-actions

This issue was automatically closed due to inactivity.

Hello all,

I’ve been trying to figure out this actioncable Websocket error I’m getting on production in an AWS EB environment on an Application Load Balancer. It’s a 404 error and also Failed to Upgrade Websocket in the logs. I’ve tried possibly the first 5 pages of google and even Bing results looking for answers. I’ve also configured the nginx.conf file in many different ways in suggestions. Seems like no one wants to attempt to help on StackOverflow.

Here’s a link to my SO post for more information: https://stackoverflow.com/questions/53566797/actioncable-websocket-upgrade-and-404-error

Here’s my current nginx configuration file, inside conf.d/default.conf:

upstream backend {

server unix:///var/run/puma/my_app.sock;

}

server {

listen 80;

access_log /var/log/nginx/access.log;

error_log /var/log/nginx/error.log;

large_client_header_buffers 8 32k;

location / {

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;

proxy_buffers 8 32k;

proxy_buffer_size 64k;

proxy_pass http://backend;

proxy_redirect off;

location /assets {

root /var/app/current/public;

}

# enables WS support

location /cable {

proxy_pass http://backend;

proxy_http_version 1.1;

proxy_set_header Upgrade websocket;

proxy_set_header Connection Upgrade;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

}

}

After running an nginx -t, this is the following readout:

nginx: [alert] could not open error log file: open() «/var/log/nginx/error.log» failed (13: Permission denied)

2018/12/10 18:42:30 [warn] 4638#0: the «user» directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:5

2018/12/10 18:42:30 [warn] 4638#0: conflicting server name «localhost» on 0.0.0.0:80, ignored

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

2018/12/10 18:42:30 [emerg] 4638#0: open() «/var/run/nginx.pid» failed (13: Permission denied)

nginx: configuration file /etc/nginx/nginx.conf test failed

I appreciate the help and you reading this.

I face this error while using channels for WebSockets on django production:

WebSocket connection to 'wss://domain.me/ws/orders/confirm_all/' failed: Error during WebSocket handshake: Unexpected response code: 404

while there’s no problem on localhost ( with runserver command )

routing.py:

from django.conf.urls import url

from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from management.consumers import ConfirmAllOrdersConsumer

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter([
            url(r'ws/orders/confirm_all/$', ConfirmAllOrdersConsumer),

        ])
    ),
})

js:

const ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";

const ordersSocket = new WebSocket(
    ws_scheme + '://'
    + window.location.host
    + '/ws/orders/confirm_all/'
);

consumers.py:

import json
from channels.generic.websocket import WebsocketConsumer
from orders.models import Orders
from time import sleep


class ConfirmAllOrdersConsumer(WebsocketConsumer):

    def connect(self):
        self.accept()

    def disconnect(self, code):
        self.disconnect(code)

    def receive(self, text_data=None, bytes_data=None):
        text_data_json = json.loads(text_data)
        action = text_data_json['action']

        if action == 'confirm_all':
            revision_orders = Orders.objects.filter(status__exact='revision')
            for idx, order in enumerate(revision_orders):
                print(idx)
                order.status = 'confirmed'
                order.save()
                sleep(0.33)

                self.send(json.dumps({
                    'total_orders': revision_orders.count(),
                    'new_val': idx + 1
                }))


it’s working on localhost over http/ws, but not working over https/wss on production


I guess it’s from apache config, not script codes, so here is my apache2 config:

Apache2 website.conf

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.

        ServerName example.com
        ServerAlias www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf

RewriteEngine on
RewriteCond %{SERVER_NAME} =www.example.com [OR]
RewriteCond %{SERVER_NAME} =example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

Apache2 website-le-ssl.conf

<IfModule mod_ssl.c>
<VirtualHost *:443>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.

        ServerName example.com
        ServerAlias www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html


    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www. [NC,OR]
    RewriteCond %{HTTPS} !on
    RewriteCond %{HTTP_HOST} ^(?:www.)?(.+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

        #RewriteEngine On
        #RewriteCond %{HTTP_HOST} ^www.example.com [NC]
        #RewriteRule ^/(.*)$ https://example.com/$1 [L,R=301]

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf

    Alias /static /home/user/website/static
    <Directory /home/user/website/static>
        Require all granted
    </Directory>

        Alias /media /home/user/website/media
        <Directory /home/user/website/media>
                Require all granted
        </Directory>

    <Directory /home/user/website/my_project/>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIScriptAlias / /home/user/website/my_project/wsgi.py
    WSGIDaemonProcess website_app python-path=/home/user/website python-home=/home/user/website/venv
    WSGIProcessGroup website_app
    
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>
</IfModule>

Any idea? Thank you.

Понравилась статья? Поделить с друзьями:
  • 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