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 \React\Socket\SocketServer('127.0.0.1:3030');
$socket->on('connection', function(\React\Socket\ConnectionInterface $connection) {
echo '[' . $connection->getRemoteAddress() . ' connected]' . PHP_EOL;
});
Second file test2.php
<?php
include 'vendor/autoload.php';
$socket = new \React\Socket\SocketServer('127.0.0.1:3031');
$connector = new \React\Socket\Connector();
$connector->connect('127.0.0.1:3030')
->then(function(\React\Socket\ConnectionInterface $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?
The
tcp://127.0.0.1:61594is actually the address of the client socket here and127.0.0.1:3031the address of the server socket which is addressed by incoming connections.When connecting to
127.0.0.1:3030theSocketServer('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 case61594).I hope this helps.