Monday, December 26, 2022

My own server client PHP

<?php
// Set up the server
$server = stream_socket_server("tcp://0.0.0.0:8080", $errno, $errorMessage);
if ($server === false) {
    throw new Exception($errorMessage);
}

// Wait for a client to connect
$client = stream_socket_accept($server);

// Read the request from the client
$request = fread($client, 1024);
echo "Request from client: " . $request . "\n";

// Send a response to the client
$response = "Hello from the server!";
fwrite($client, $response);

// Close the connection
fclose($client);

***********


//Set up the client

<button onclick="sendRequest()">Send request</button>
<script>
function sendRequest() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            alert(this.responseText);
        }
    };
    xhttp.open("POST", "server.php", true);
    xhttp.send("Hello from the client!");
}
</script>

No comments:

Post a Comment

Коментар: