Skip to content
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

Ratchet demo is not working with browser #1017

Open
varun7952 opened this issue Jun 3, 2023 · 0 comments
Open

Ratchet demo is not working with browser #1017

varun7952 opened this issue Jun 3, 2023 · 0 comments

Comments

@varun7952
Copy link

I am following official [Ratchet guide to create websocket connection with server. I can connect and exchange message to the websocket with the terminal using telnet and also with windows telnet. But i failed to connect with the postman or browser.

Postman:- URL:- ws://example.com:8080 Connection status stuck at connecting. Logs in terminal:-


New connection! (4)
Connection 4 sending message "GET / HTTP/1.1
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 7tDexklCqe0qVktlDsYz6w==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: example.com:8080

" to 0 other connections

Firefox Browser console in black tab (following the guide from ratchet)

var conn = new WebSocket('ws://example.com:8080');
conn.onopen = function(e) {
    console.log("Connection established!");
};

conn.onmessage = function(e) {
    console.log(e.data);
};

Error/Response received

Content Security Policy: The page’s settings blocked the loading of a resource at ws://example.com:8080/ (“default-src”). debugger eval code:1:11
Uncaught NS_ERROR_CONTENT_BLOCKED:
debugger eval code:1
debugger eval code:1:12

Server code to create websocket

<?php
// Enable error reporting and display errors for debugging purposes
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once("/home/bitnami/vendor/autoload.php");
use Ratchet\MessageComponentInterface;;
use Ratchet\ConnectionInterface;

class WebSocketHandler implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage();
        print_r("Print Value ");
    }

    public function onOpen(ConnectionInterface $conn) {
        // Handle new WebSocket connection
        // You can add the connection to $this->clients for future reference
        //$request = $conn->httpRequest;
        //$userId = $_POST['userId']; // Assuming the user ID is received in the POST request

        // Save the user ID in the resourceId property of the connection
        $conn->resourceId = $userIdA;

        // Add the connection to the clients list
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        // Handle incoming WebSocket message
        // You can process the message and send a response back to the client
    }

    public function onClose(ConnectionInterface $conn) {
        // Handle WebSocket connection close
        // You can remove the connection from $this->clients if necessary
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        // Handle WebSocket error
        // You can log or handle the error as needed
    }
}



// Get the SDP and user IDs from the request
$sdp = $_POST['sdp'];
$userIdA = $_POST['userIdA'];
$userIdB = $_POST['userIdB'];

// Fetch user details from the elaxer database using the user IDs
$userDetailsA = fetchUserDetails($userIdA);
$userDetailsB = fetchUserDetails($userIdB);

// Send push notification to wake up User B's device
//sendPushNotification($userDetailsB['fcmToken']);

// Wait for User B's device to establish a WebSocket connection
$waitForConnectionTimeout = 30; // Timeout in seconds
$startTime = time();
while (time() - $startTime < $waitForConnectionTimeout) {
    // Check if User B's device has connected to the WebSocket
    if (userDeviceConnected($userIdB)) {
        // User B's device connected, retrieve SDP from the elaxer database
        $sdpB = fetchSDP($userIdB);

        // Save User A's SDP in the elaxer database
        saveSDP($userIdA, $sdp);

        // Return User B's SDP to User A
        echo $sdpB;
        exit;
    }

    // Wait for a short duration before checking again
    sleep(1);
}


// Instantiate WebSocketHandler

//$server = \Ratchet\Server\IoServer::factory(
  //  new \Ratchet\Http\HttpServer(
    //    new \Ratchet\WebSocket\WsServer($webSocketHandler)
    //),
    //8080 // Change the port number if needed
//);

// Set up the WebSocket server using Ratchet
$server = Ratchet\Server\IoServer::factory(new WebSocketHandler(),20081); // Change the port number if needed
$server->run();




// Timeout reached, handle the case when User B's device didn't connect
handleTimeout();

// Fetch user details from the elaxer database using the user ID
function fetchUserDetails($userId)
{
    // Implement the logic to fetch user details from the elaxer database
    // Return an array containing the user details
}

// Send push notification to wake up User B's device
function sendPushNotification($fcmToken)
{
    // Implement the logic to send a push notification using FCM to the specified FCM token
}

// Check if User B's device has connected to the WebSocket
function userDeviceConnected($userId)
{
    // Implement the logic to check if User B's device has connected to the WebSocket
    // Return true if the device is connected, false otherwise
}

// Fetch SDP from the elaxer database using the user ID
function fetchSDP($userId)
{
    // Implement the logic to fetch SDP from the elaxer database using the user ID
    // Return the retrieved SDP
}

// Save SDP in the elaxer database using the user ID
function saveSDP($userId, $sdp)
{
    // Implement the logic to save the SDP in the elaxer database using the user ID
}

// Handle the case when User B's device didn't connect within the timeout
function handleTimeout()
{
    // Implement the logic to handle the timeout case
    // For example, you can return an error response or perform a fallback action
}


?>

To start a socket code:-

php bin/callSocketChat_2008.php

(For postman, it might be issue with postman but i am not sure.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant