How to make this socket server work in PHP?

I am creating a server with PHP sockets, I have created the server file.php and I have uploaded it to my VPS. I created a client.php to test and I open it from localhost, the case is that it always tells me that it is impossible to connect to the server via port 10000.

These are the codes (they are very simple to test).

Server.php

#!/usr/local/bin/php -q
<?php
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,'127.0.0.1',10000);
socket_listen($socket);

echo "Esperando conexión\n\n";
$conn = false;
switch(@socket_select($r = array($socket), $w = array($socket), $e = array($socket), 60)) {
case 2:
echo "Conexión rechazada!\n\n";
break;
case 1:
echo "Conexión aceptada!\n\n";
$conn = @socket_accept($socket);
break;
case 0:
echo "Tiempo de espera excedido!\n\n";
break;
}
if ($conn !== false) {
  socket_write($conn, "TE HAS CONECTADO PERFECTAMENTE", srtlen("TE HAS CONECTADO PERFECTAMENTE"));
}
?>

Client.php

<?php
$host = "IP DE MI VPS";

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$puerto = 10000;

if (socket_connect($socket, $host, $puerto))
{
echo "\nConexion Exitosa, puerto: " . $puerto;
$out = socket_read($socket, 2048);
echo $out;
}
else
{
echo "\nLa conexion TCP no se pudo realizar, puerto: ".$puerto;
}
socket_close($socket);
?>

To leave the server open as a daemon in linux I use the command:

nohup php servidor.php > errores.log &

I don't know why it doesn't make the connection, I guess it will open to open the port or something. It's the first time I've tried to do something like this.

 4
Author: Jesús, 2016-05-12

2 answers

One of several problems is that when doing

socket_bind($socket,'127.0.0.1',10000);

The socket only listens to connections on ip 127.0.0.1 (i.e. local). If you want me to listen on the public IP, you must use that IP. Or use ' 0.0.0.0', which involve listening in all available directions.

On the other hand, if the server is public it most likely has a firewall that filters incoming connections (otherwise it would be very worrying), so you should make sure that that port allows incoming connections.

Another thing: the @ as a prefix in PHP function calls makes warnigs and error messages not visible. In general, it is bad practice. And even more so when you're trying to debug or understand why something isn't working. My advice is not to use it almost never.

 3
Author: leonbloy, 2016-06-17 20:30:08

Try that please:

If you put the public IP of the VPS in server and client script you would have to work if you fix this little error:

Srtlen - > strlen

$ php ./socketclient.php

Conexion Exitosa, puerto: 10000TE HAS CONECTADO PERFECTAMENTE

You cannot access a server from outside without using its IP. And the server script also has to use the public IP.

 0
Author: mart, 2016-05-18 16:58:22