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

Any logs generated by Ratchet for debugging #1023

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

Any logs generated by Ratchet for debugging #1023

varun7952 opened this issue Jun 19, 2023 · 3 comments

Comments

@varun7952
Copy link

varun7952 commented Jun 19, 2023

I am connecting to the websocket from android app with the help of okhttp library. I tried to look for the logs to debug when some user disconnects automatically. The android app okhttp shows this at onFailure, that is not enough to debug the code why user get disconnected.

onFailure: Attempt to invoke virtual method 'java.lang.String[] java.lang.String.split(java.lang.String)' on a null object reference.

This is websocket server code (Ratchet Websocket Library). From android app i can connect with the server but i think there is some issue in this code.

What actually happening :-

When User A Connect with the server onOpen calls as expected and successfully get connected but after few seconds when User B send request to connect to the websocket server, User B get connect and kicks User A out (Disconnect User A) from the server. Can you check if there is any issue with this code? or how i can debug the issue.

<?php
require_once("/home/bitnami/vendor/autoload.php");
include('classes/notification.php');
use Ratchet\MessageComponentInterface;;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;

class WebSocketHandler implements MessageComponentInterface {
    protected $clients;

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

    public function onOpen(ConnectionInterface $conn) {
        // Handle new WebSocket connection
        // You can add the connection to $this->clients for future reference
			
		$request = $conn->httpRequest;
		// Get the action
        $action = $request->getHeaderLine("action");
        // Check if the action is "addClient"
        if ($action === "addClient") {
            // Add the user to the list of connected users
            $userId = $request->getHeaderLine('userId');			
			// Save the user ID in the resourceId property of the connection
			$conn->resourceId = $userId;
			// Add the connection to the clients list
			$this->clients->attach($conn, $userId);
			
			// Store the connected user in the file
            $connectedUsers = $this->getConnectedUsers();
            $connectedUsers[$userId] = true;
            $this->saveConnectedUsers($connectedUsers);
        }
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        // Handle incoming WebSocket message
        // You can process the message and send a response back to the client
		
		$data = json_decode($msg, true); // Assuming the message is in JSON format
                
		// Extract the user ID from the message
		$myUserID = $data['myID']; 
		$otherUserID = $data['otherID'];
		
        // Find the connection of User B in the clients list
        $recipientConnection = $this->findClientConnection($otherUserID);
        if ($recipientConnection !== null) {
            // Send the response message to User B
            $recipientConnection->send(json_encode($response));
        }
		
    }

	public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);
				
		// Remove the disconnected user from the file
        $userId = $conn->resourceId;
        $connectedUsers = $this->getConnectedUsers();
        unset($connectedUsers[$userId]);
        $this->saveConnectedUsers($connectedUsers);

    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
		file_put_contents('zee_Error1.log',print_r($e,true));
        $conn->close();
    }
	
	private function findClientConnection($userId) {
        foreach ($this->clients as $client) {
            if ($client->resourceId === $userId) {
                return $client;
            }
        }
        return null;
    }  	
	
	private function saveConnectedUsers($connectedUsers) {
        $file = 'z_connected_users.txt';
        file_put_contents($file, serialize($connectedUsers));
    }
	
	private function getConnectedUsers() {
        $file = 'z_connected_users.txt';
        if (file_exists($file)) {
            $connectedUsers = unserialize(file_get_contents($file));
            return is_array($connectedUsers) ? $connectedUsers : [];
        }
        return [];
    }
	
}
    


	$server = IoServer::factory(
			new HttpServer(
				new WsServer(
					new WebSocketHandler()
				)
			),
			8080
		);


    $server->run();
@SimonFrings
Copy link

Hey @varun7952, thanks for bringing this up 👍

I tried to look for the logs to debug when some user disconnects automatically...

There is no logging in Ratchet by default, this would otherwise cause a lot of overhead for users who aren't interested in a logging mechanism. Ratchet itself is a multi-layered project, so you could also create and add your own logging adapter to see what's happening behind the scenes.

User B get connect and kicks User A out (Disconnect User A) from the server. Can you check if there is any issue with this code?

It's definitely odd that User A gets disconnected, this means that either client or server closes the connection, but based on the fact that this is happening when a second user connects, my guess would be that it's server side related. I don't see anything obvious in your code base and the only time you call a $conn->close() is in onError(). Does every new user "kick out" an already connected one?

@varun7952
Copy link
Author

@SimonFrings Thanks for the response.
When someone disconnect from server automatically/intentionally then as for debug i need to know the reason for the disconnection so i can fix it. The error never get called and it closed just by calling onClose() .

Is there any way to get the reason for disconnection at onClose?

@Cepairda
Copy link

Cepairda commented Oct 8, 2023

Я подключаюсь к веб-сокету из приложения Android с помощью библиотеки okhttp. Я пытался найти журналы для отладки, когда какой-то пользователь автоматически отключается. Приложение для Android okhttp показывает это в onFailure, этого недостаточно для отладки кода, почему пользователь отключается.

onFailure: попытка вызвать виртуальный метод «java.lang.String[] java.lang.String.split(java.lang.String)» по нулевой ссылке на объект.

Это код сервера веб-сокетов (библиотека веб-сокетов Ratchet). Из приложения Android я могу подключиться к серверу, но думаю, что в этом коде есть какая-то проблема.

Что на самом деле происходит: -

Когда пользователь A подключается к серверу onOpen, как и ожидалось, и успешно подключается, но через несколько секунд, когда пользователь B отправляет запрос на подключение к серверу веб-сокетов, пользователь B подключается и выгоняет пользователя A (отключает пользователя A) с сервера. Можете ли вы проверить, есть ли какие-либо проблемы с этим кодом? или как я могу устранить проблему.
@varun7952 HI, were you managed to solve the problem?

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

3 participants