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
The
tcp://127.0.0.1:61594
is actually the address of the client socket here and127.0.0.1:3031
the address of the server socket which is addressed by incoming connections.When connecting to
127.0.0.1:3030
theSocketServer('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.
If our
test2.php
should act as a client, theSocketServer
is not needed.In order to bind a port to your client connection, do:
This will use port
12345
for your client connection.See also https://www.php.net/manual/context.socket.php.