1

I'm building a simple chat application using Ratchet PHP Libray, And when a user enters a message it is stored in the database then displayed .However,the user cannot receive supposedly sent messages by other users,here is the relevant part of code:

server.php ( Important function is onMessage that is responsibel for receving and sending messages back to user ) :

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
    protected $clients;
    protected $userConnections;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
        $this->userConnections = [];
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        list($recipient_id, $message) = explode(':', $msg, 2);

        if (isset($this->userConnections[$recipient_id])) {
            echo "Received message for User ID {$recipient_id}: {$message}\n";

            $recipientConn = $this->userConnections[$recipient_id];
            $recipientConn->send($message);
        }
        
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";

        $userId = array_search($conn, $this->userConnections);
        if ($userId !== false) {
            unset($this->userConnections[$userId]);
        }
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
?>
chat.php:
  <?php
include("connect.php");
include("auth_check.php");

$crpyted_userId = @$_GET['user_id'];
$crypted_recipient_id = @$_GET['recipient_id'];
$recipient_id = base64_decode($crypted_recipient_id);

if ( empty($recipient_id)) {
    echo("Could not validate your request. Recipient id empty");
} else {

        ?>
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <link rel="stylesheet" href="chatroom.css">
                <title>Chat Room</title>
            </head>
            <body>
                <div class="chat-container" id="chat">
                    
                    <div class="input-container">
                        
                        <textarea type="text" id="messageInput" oninput="validateMessage()" placeholder="Type your message..." maxlength="600"></textarea>
                        <button id="send" onclick="sendMessage()"><img id="message_icon" src="uploads/message.png"></button>
                    </div>
                </div>
                <script>
                    function validateMessage() {
                        var sendButton = document.getElementById('send');
                        var message = document.getElementById('messageInput').value.trim();
                        var isValid = message.length > 0 && message.length <= 600;
                        sendButton.disabled = !isValid;
                        return isValid;
                    }
                    
                    validateMessage();

                    const socket = new WebSocket('ws://localhost:8080');
                    const chatContainer = document.getElementById('chat');
                    chatContainer.scrollTop = 0;

                    function updateScroll() {
                        chatContainer.scrollTop = chatContainer.scrollHeight;
                    }

                    socket.onmessage = function (event) {
                        console.log("testing:");
                        chatContainer.innerHTML += '<div class="message recipient"><div class="message-content"><p>' + event.data + '</p></div></div>';
                        updateScroll();

                    };

                    function sendMessage() {
                        if (validateMessage()) {
                            const messageInput = document.getElementById('messageInput');
                            const message = messageInput.value;

                            var messageData = new FormData();
                            messageData.append('message', message);
                            messageData.append('messages', 'one');
                           
                            messageData.append('recipient_id', <?php echo $recipient_id ?>);
                            var xhr = new XMLHttpRequest();
                            xhr.open('POST', 'messageHandling.php', true);

                            xhr.onload = function () {
                                if (xhr.readyState === 4 && xhr.status === 200) {
                                    const jsonResponse = JSON.parse(xhr.responseText);
                                    const message = jsonResponse.message;
                                    //important when cannot process json response
                                    socket.send(<?php echo json_encode($recipient_id); ?> + ':' + message);
                                    chatContainer.innerHTML += '<div class="message sender"><div class="message-content"><p>' + message + '</p></div></div>';
                                    updateScroll();
                                }
                            };

                            xhr.send(messageData);
                        }
                    }
               
                    document.addEventListener("DOMContentLoaded", function() {
                        var xhr = new XMLHttpRequest();
                        var messageData = new FormData();
                        messageData.append('recipient_id', <?php echo $recipient_id?>);
                        messageData.append('messages', 'all');  // Include 'messages' in FormData

                        xhr.open('POST','messageHandling.php', true);
                        xhr.onload = function(){
                            if(xhr.readyState === 4 && xhr.status === 200){
                                var messages = JSON.parse(xhr.responseText);
                                socket.onopen = function(){
                                    for (const msg of messages) {
                                        socket.send(<?php echo json_encode($recipient_id); ?> + ':' + msg);
                                        chatContainer.innerHTML += '<div class="message sender"><div class="message-content"><p>' + msg + '</p></div></div>';
                                        updateScroll();
                                    }
                                }
                            }
                        }
                        xhr.send(messageData);
                    });
                </script>
            </body>
            </html>
            <?php
        }
    

?>

3
  • Please post all the HTML code (not just the JS socket.onmessage part) Commented Jan 14, 2024 at 16:29
  • @KenLee,I've provided it.Please check it. Commented Jan 14, 2024 at 17:45
  • @KenLee,any ideas ? Commented Jan 17, 2024 at 19:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.