Reputation: 11
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?
Upvotes: 0
Views: 393
Reputation: 377
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 \React\Socket\Connector(
['tcp' => ['bindto' => '127.0.0.1:12345']] // ip:port here
);
$connector->connect('127.0.0.1:3030')
->then(function(\React\Socket\ConnectionInterface $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.
Upvotes: 0
Reputation: 142
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.
Upvotes: 0