Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping PHP Server socket alive after connection

Tags:

php

sockets

xampp

I have a Server socket page that basically receives a string, reverses it and sends it back to the client, that works perfect, the socket however closes after the connection, tried fixing this but to no avail, can anyone please tell me what I'm doing wrong?

    $host = "192.168.8.121";
    $port = 232;

    set_time_limit(0);

    $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");

    $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");

    $result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

    $spawn = socket_accept($socket) or die("Could not accept incoming connection\n");

    $input = socket_read($spawn, 1024) or die("Could not read input\n");


    $input = trim($input);
    echo "Client Message : ".$input;

    // reverse client input and send back
    $output = strrev($input) . "\n";
    socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");

    // close sockets
    socket_close($spawn);
    socket_close($socket);
like image 601
Lappies Avatar asked Oct 06 '26 20:10

Lappies


1 Answers

You need a socket read loop:

function error($socket) {
    return socket_strerror(socket_last_error($socket));
}

$host = "127.0.0.1";
$port = 1024;

set_time_limit(0);

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or
          die(__LINE__ . ' => ' . error($socket));

$result = socket_bind($socket, $host, $port) or
          die(__LINE__ . ' => ' . error($socket));

$result = socket_listen($socket, 3) or
          die(__LINE__ . ' => ' . error($socket));

$spawn = socket_accept($socket) or
         die(__LINE__ . ' => ' . error($socket));

while(true) {

    $input = socket_read($spawn, 1024) or
             die(__LINE__ . ' => ' . error($socket));

    $input = trim($input);

    if ($input == 'exit') {
        echo 'exiting from server socket read loop';
        break;
    }

    echo "Client Message : " . $input . '<br>';

    // reverse client input and send back
    $output = strrev($input) . "\n";
    socket_write($spawn, $output, strlen($output)) or
    die(__LINE__ . ' => ' . error($socket));

}

// close sockets
socket_close($spawn);
socket_close($socket);
like image 195
Agnius Vasiliauskas Avatar answered Oct 09 '26 10:10

Agnius Vasiliauskas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!