reacrphp/socket closing connection

Advertisements

This is inside a Laravel 11 default project using the reactphp/socket TcpServer the socket doesn’t connect from client open.

Here’s the code.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use React\EventLoop\loop as EventLoop;
use React\Socket\ConnectionInterface;
use React\Socket\TcpServer;

class SocketTest extends Command
{
    protected $signature = 'socket:test';
    protected $description = 'Run asynchronous socket server';
    public function handle()
    {
        $loop = EventLoop::get();
        $socket = new TcpServer('0.0.0.0:8001', $loop);
        $socket->on('connection', function (ConnectionInterface $connection) {
            echo ($connection->getRemoteAddress() . " Connected \n");
            $connection->on('data', function ($data) use ($connection) {
                $connection->write($data . "\n");
            });
            $connection->on('end', function () use ($connection) {
                echo ($connection->getRemoteAddress() . " Ended \n");
            });
            $connection->on('close', function () use ($connection) {
                echo ($connection->getRemoteAddress() . " Closed \n");
            });
            $connection->on('error', function (\Exception $exception) use ($connection) {
                echo ($connection->getRemoteAddress() . " Error \n");
                var_dump($exception);
            });
        });
        $loop->run();
    }
}

Using php artisan socket:test to start up the socket.

Using WebSocket Test Client to Test the connection on ws://127.0.0.1:8001

Terminal that’s running the server outputs

tcp://127.0.0.1:62658 Connected
tcp://127.0.0.1:62658 Ended
tcp://127.0.0.1:62658 Closed

Output of Chrome Devtools:

WebSocket connection to 'ws://127.0.0.1:8001/' failed: 

>Solution :

ReactPHP core maintainer here. Looks like you’re trying to connect to a TCP socket with a WebSocket client. If you’re looking to add WebSocket support to your application have a look at https://reactphp.org/http/#server-usage with https://github.com/voryx/WebSocketMiddleware. If you’re looking for TCP communication https://reactphp.org/socket/#connection-usage can help you with that.

Leave a ReplyCancel reply