PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 13, 2022

[FIXED] How to catch a php websocket broken TCP connection exception with Amphp?

 April 13, 2022     amphp, php, phpwebsocket, websocket     No comments   

Issue

Here is the current WebSocket loop I'm running while the connection is still alive. But after 11 hours of continuous connection, I received an exception

"exception":"[object] (Amp\\Websocket\\ClosedException(code: 1006): The connection was closed: Client closed the underlying TCP connection at ...

How can I check for the closed connection or the exception itself?, this way I can properly end the script logic without an abrupt failure.

     \Amp\Loop::run(function () use ($fn, $st)
        {
            $connection = yield \Amp\Websocket\connect('wss://URL');

            yield $connection->send('{"action":"auth","params":"KEYID"}');
            yield $connection->send('{"action":"subscribe","params":"'.$st.'"}');

            $i = 0;

            while ($message = yield $connection->receive()) 
            {
                $i++;
                $payload = yield $message->buffer();

                $r = $fn($payload, $i);

                if ($r == false) {
                    $connection->close();
                    break;
                }
            }
        }
    );

I am using this Amphp Websocket: https://github.com/amphp/websocket-client

Thanks!


Solution

I did find a solution to this by looking for the ClosedException and running other tasks after it has been thrown.

\Amp\Loop::run(function () use ($fn, $st)
    {
        try 
        {
            $connection = yield \Amp\Websocket\connect('wss://URL');

            yield $connection->send('{"action":"auth","params":"KEYID"}');
            yield $connection->send('{"action":"subscribe","params":"'.$st.'"}');

            $i = 0;

            while ($message = yield $connection->receive()) 
            {
                $i++;
                $payload = yield $message->buffer();

                $r = $fn($payload, $i);

                if ($r == false) {
                    $connection->close();
                    break;
                }
            }
        }
        catch (\Amp\Websocket\ClosedException $e) 
        {
            // do something here
        }
    }
);


Answered By - tmarois
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing