samedi 28 mars 2020

How can I write TCP queries on my server? What I have written wrong?

I need to send TCP queries on my server (I want to make capability multiple connections, later), but my server don't receive anything and I haven't got any error. Server should receive every message of client. Anybody shouldn't disconnect ever. Client should have capability to send second message after first without reconnection.

server.php

<?php

$address = 'localhost';
$port = 10000;

set_time_limit(0);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
socket_bind($socket, $address, $port) or die("Could not bind to socket\n");
socket_listen($socket, 3) or die("Could not set up socket listener\n");

$clients = [];

while (true) {
    $newSocket = socket_accept($socket) or die("Could not accept incoming connection\n");
    if (is_resource($newSocket)) {
        //socket_set_nonblock($newSocket);
        echo "New client connected\n";
        $clients[] = $newSocket;
        socket_read($newSocket, 1024, PHP_NORMAL_READ) or die("Could not read input\n");
        sleep(1);
    }
}

client.php

<?php

$address = 'localhost';
$port = 10000;

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
socket_connect($socket, $address, $port) or die("Could not connect to server\n");

while (true) {
    $input = readline();
    $input .="\n";
    socket_write($socket, $input, strlen($input)) or die("Could not send data to server\n");
    sleep(1);
}



Aucun commentaire:

Enregistrer un commentaire