WebSocket connection to failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT

user1 picture user1 · Apr 9, 2019 · Viewed 10.6k times · Source

Good day guys

I'm building a chat app using ratchet and save data to mysql database. On localhost everything is working well and connection is established.

Now I have loaded the app on live server and login using SSH (Putty), then navigated to php bin/chat-server.php then on the browser console I get this error :

WebSocket connection to 'wss://donorgametes.com:8080/' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT

This is my url to the app

https://donorgametes.com/MyApp/

My code :

<script>
    var conn = new WebSocket('wss://donorgametes.com:8080');
    conn.onopen = function (e) {
        console.log("Connection established!");

    };

    conn.onmessage = function (e) {
        showMessage(e.data, 'Others');
    };

    document.querySelector('#chat-form').addEventListener('submit', function (e) {
        e.preventDefault();

        var messageElement = document.querySelector('#message');
        var message = messageElement.value;

        var messageData = {
            'userId': '12',
            'content': message
        }
        var messageDataJson = JSON.stringify(messageData);

        conn.send(JSON.stringify(messageDataJson));
        showMessage(message, 'Me');
        messageElement.value = '';
    });

    function showMessage(msg, sender) {
        var messageItem = document.createElement('li');
        var className = 'list-group-item';

        if (messageItem.classList)
            messageItem.classList.add(className);
        else
            messageItem.className += ' ' + className;

        messageItem.innerHTML = '<strong>' + sender + ': </strong>' + msg;
        document.querySelector('#chat-area > ul').appendChild(messageItem);
    }
</script>

Chat server

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()
        )
    ),
    8080
);

$server->run();

How can I run this on live server and get a connection? What steps must I follow?

Answer

Touqeer Shafi picture Touqeer Shafi · Apr 25, 2019

After checking your app page source i found that you are using localhost for connection on line number: 38

var conn = new WebSocket('wss://localhost:8080');

Which is wrong, you should use your own domain name.

Second thing is after checking port forwarding on you domain i have found that port 8080 is blocked right now. So you should better ask your hosting provider to open port in IPTABLES for incoming connections or if you have root access then try this Article it might help you to allow port forwading.