Unable to establish connection via web socket with SSL and WSS in JavaScript

Below is the code I used to implement web socket:

try {
        console.log('wss://' + hostname + ':' + port + endpoint);
        webSocket = new WebSocket(webSocketURL);
        webSocket.onmessage = function (event) {
            //console.log('send message successfully.');
            var obj = JSON.parse(event.data);
            append_data(obj, market_pair);
        };
    } catch (exception) {
        console.log('Exception handle!');
        console.error(exception);
    }

Although my page supports HTTPS and I am using the wss protocol, I encountered an error stating that "Firefox can’t establish a connection to the server at wss://domainname.com:4008/order.php." When I load the page using simple HTTP and ws in Websocket, it works fine. However, when using wss, it shows the above error. The same issue occurs in Google Chrome as well. My SSL certificate is properly installed on the server, and both hosting and domain are provided by GoDaddy who confirmed that the certificate was installed correctly.

The server-side socket running in PHP works perfectly; but I cannot connect to that socket port using wss://.

I discovered that I'm unable to perform the handshake with my PHP code because the content received through socket read is encrypted.

function doHandshake($received_header, $client_socket_resource, $host_name, $port) {
    echo $received_header;
    $headers = array();
    $lines = preg_split("/\r\n/", $received_header);
    foreach ($lines as $line) {
        $line = chop($line);
        if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
            $headers[$matches[1]] = $matches[2];
        }
    }

    $secKey = $headers['Sec-WebSocket-Key'];
    echo $headers['Sec-WebSocket-Key']; 
    $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    //$secAccept = base64_encode(sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'));
    $buffer = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
            "Upgrade: websocket\r\n" .
            "Connection: Upgrade\r\n" .
            "WebSocket-Origin: $host_name\r\n" .
            "WebSocket-Location: wss://$host_name:$port/websocket/btc_boon_pair.php\r\n" .
            "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
    socket_write($client_socket_resource, $buffer, strlen($buffer));
}

In my handshake function, $headers['Sec-WebSocket-Key'] is undefined due to encryption in $received_header.

Can someone suggest a solution to this issue? I need to run the PHP file as a daemon and connect using the wss protocol.

Answer №1

After wrestling with the problem for a while, I finally managed to resolve it.

The issue stemmed from the SSL encryption preventing my PHP daemon file from reading the socket. Fortunately, I found a solution in the following answer:

By utilizing proxy pass in Apache, all requests with '/websocket' were able to be sent to 'ws://host:port/', resulting in seamless functionality.

It's worth noting that the domain name should not be using a proxy, as this was causing the initial solution to fail. Once the proxy was removed from DNS settings, everything started working smoothly.

Answer №2

My particular situation involved utilizing a VPS from Dreamhost.com, which meant that I was unable to modify Apache configuration files. Despite this limitation, I successfully initiated a secure socket server by employing the library noted below:

use WSSC\Components\ServerConfig;
use WSSC\WebSocketServer;

$config = new ServerConfig();
$config->setIsSsl(true)->setAllowSelfSigned(true)
    ->setCryptoType(STREAM_CRYPTO_METHOD_SSLv23_SERVER)
    ->setLocalCert("./tests/certs/cert.pem")->setLocalPk("./tests/certs/key.pem")
    ->setPort(8888);

$websocketServer = new WebSocketServer(new ServerHandler(), $config);
$websocketServer->run();

To gather the necessary information for cert.pem and key.pem, I extracted proper values from the Secure Certificates section within the Dreamhost dashboard accessed via Websites.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhanced coding experience with JavaScript completion and ArangoDB module management

Exploring New Horizons After more than a decade of using Eclipse for Java development, I have decided to delve into the realms of javascript and arangodb due to high demand. My current task involves developing multiple microservices to run within arangodb ...

How can the front design of Material-UI's Card header be customized?

Currently, I am facing an issue with the Material-UI card header as the background color is affecting the readability of the default font. My aim is to use the typography prop h4 for the header, but I am struggling to achieve this. https://i.stack.imgur.c ...

Node.js local storage/cookie functionality

Running three different apps on Node.js at ports 3000, 3005, and 3007. I need to set a LocalStorage or Cookie variable at port 3000 and access it from the apps running at ports 3005 and 3007. Folder structure: nodep/ |-app.js (runs at port 30 ...

To link circles vertically with a line and fill them with color when clicked, follow these steps:

I am looking to create a design similar to the image below using unordered list items. When a user clicks on a list item, I want the circle to fill with color. I have structured it by creating a div with nested list items and span elements. If a user click ...

Adding information to a database by utilizing Jquery, Ajax, and PHP

Trying to use ajax to submit data to a database has been a challenge for me. Even with a simple code test, I can't seem to make it work. Here is the HTML/ajax code snippet: <?php include("osb.php");?> <script type = "text ...

Why isn't my custom HTML attribute displaying correctly?

In my current React app project, I have been incorporating custom attributes to HTML tags and React components for End-to-End (E2E) tests using Testcafe. However, I am facing an issue where the additional data-test="burger-menu-btn" attribute is ...

Develop a plugin architecture using JavaScript and Node.js

Here is a basic implementation using node.js with express: var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000); I am interested in creatin ...

Problem with escaping special characters in random string HTML

As I was in the process of creating a JavaScript tool to generate random strings, with or without special characters, I stumbled upon an inspiring snippet that caught my attention: (): function randStr(len) { let s = ''; while (len--) s += ...

What is the best way to unselect the "all" selector if one of the inputs is no longer selected?

I am facing an issue with a search filter functionality. When all filters are selected and then deselected individually or together, the "all" button remains selected. I need help in ensuring that when any filter is deselected, the "all" button also gets d ...

What is the best way to identify the differences between two non-unique arrays in JavaScript? I initially relied on underscore, but I am willing to

Given two arrays: firstArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}] secondArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}] The expected output is [{id:'id3'}] This ...

Don't allow users to switch views without saving their changes

We are working with a Backbone.js application that presents various forms to users. Our goal is simple: if a user navigates away from the page without saving the completed form, we need to show a confirmation dialog. When dealing with traditional forms, i ...

Does Google's web crawler have the ability to index content created by javascript?

Our web app generates content using javascript. Can Google index these pages? In our research on this issue, we primarily found solutions on older pages suggesting the use of "#!" in links. Within our app, the links are structured as follows: domain.co ...

Unable to place within div

Utilizing HTML5 to implement the "DnD" function. There is a button that adds divs. I want to be able to drag items into these newly added divs. Currently, I can only drag into existing divs and not the ones added later. How can I resolve this issue ...

PHP, jQuery, and MySQL combine to create a powerful autocomplete feature for your

I've implemented the source code from into my project, but I'm facing an issue where I can't retrieve any results when typing in the autocomplete textbox. Could someone point out where I might be making a mistake? This is the code I am us ...

Changing a transparent div with overlays into a visual representation of its underlying background

I am curious to know if it is feasible to carry out the operation mentioned, given that JavaScript doesn't currently have access to the contents of certain objects, such as a Flash video player. I have explored various screenshot plugins, but none of ...

Utilizing StyleFunctionProps within JavaScript for Chakra UI Enhancements

I need help figuring out how to implement StyleFunctionProps in my Chakra UI theme for my NextJS project. The documentation on Chakra's website provides an example in Typescript, but I am working with Javascript. Can someone guide me on adapting this ...

What is the reason for npm and yarn to download multiple versions of jquery?

For the purpose of investigating how package managers like npm, yarn, and cnpm work in Node.js, I conducted an experiment. During the test, I came across two packages: jquery-dreamstream and jquery.tree. Both of them have a dependency solely on jquery wit ...

Combining package.json commands for launching both an Express server and a Vue app

I recently developed an application using Vue.js and express.js. As of now, I find myself having to open two separate terminal windows in order to run npm run serve in one and npm start in the other. My ultimate goal is to streamline this process and have ...

verify access with mysql database

Need urgent assistance, sorry if this is a repeated query due to my username! I am facing an issue with my login page. I want it to redirect to my home page when authentication fails by cross-checking input with a MySQL database which should output succes ...

The problem with utilizing the Node `util.inherits` method

I have encountered an issue with a 'this problem' in a Node server. It seems that replacing worker.stuff with worker.stuff.bind(worker) is necessary for it to function correctly. Is there a way to incorporate the bind method into the Worker Clas ...