skip to Main Content

I have two files opening a new socket and want them to connect to each other using React PHP. The following two files are the sockets:

First file test1.php

<?php

include 'vendor/autoload.php';

$socket = new ReactSocketSocketServer('127.0.0.1:3030');
$socket->on('connection', function(ReactSocketConnectionInterface $connection) {
    echo '[' . $connection->getRemoteAddress() . ' connected]' . PHP_EOL;
});

Second file test2.php

<?php

include 'vendor/autoload.php';

$socket = new ReactSocketSocketServer('127.0.0.1:3031');
$connector = new ReactSocketConnector();
$connector->connect('127.0.0.1:3030')
    ->then(function(ReactSocketConnectionInterface $connection) {
        echo '[Connected with ' . $connection->getRemoteAddress() . ']' . PHP_EOL;
    });

If I run php test1.php and then php test2.php I would expect the following outcome:

[Connected with tcp://127.0.0.1:3030]
[tcp://127.0.0.1:3031 connected]

However, the result is:

[Connected with tcp://127.0.0.1:3030]
[tcp://127.0.0.1:61594 connected]

What am I doing wrong here? How do I get React PHP to connect with the 3031 port?

2

Answers


  1. The tcp://127.0.0.1:61594 is actually the address of the client socket here and 127.0.0.1:3031 the address of the server socket which is addressed by incoming connections.

    When connecting to 127.0.0.1:3030 the SocketServer('127.0.0.1:3031') doesn’t use it’s server socket address as the client socket address, because this address is already in use. Instead your OS generates a random port number for the client socket (in this case 61594).

    I hope this helps.

    Login or Signup to reply.
  2. If our test2.php should act as a client, the SocketServer is not needed.

    In order to bind a port to your client connection, do:

    
    <?php
    
    include 'vendor/autoload.php';
    
    $connector = new ReactSocketConnector(
        ['tcp' => ['bindto' => '127.0.0.1:12345']] // ip:port here
    );
    
    
    $connector->connect('127.0.0.1:3030')
        ->then(function(ReactSocketConnectionInterface $connection) {
            echo '[Connected with ' . $connection->getRemoteAddress() . ']' . PHP_EOL;
        });
    

    This will use port 12345 for your client connection.
    See also https://www.php.net/manual/context.socket.php.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search