Creating the Client

To solve the second problem is very easy. You need to create a PHP page that connects to a socket, receive any data that is in the buffer, and process it. After you have processed the data in the buffer you can send your data to the server. When another client connects, it will process the data you sent and the client will send more data back to the server.

NOTE

This is simply an example to demonstrate a use of sockets. This is by no means production-level code to be used on a public game.

<?php
// Create the socket and connect
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connection = socket_connect($socket,’localhost’, 1337);

while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ))
{
    if($buffer == “NO DATA”)
    {
        echo(“<p>NO DATA</p>”);
        break;
    }
    else
    {
        // Do something with the data in the buffer
        echo(“<p>Buffer Data: “ . $buffer . ”</p>”);
    }
}

echo(“<p>Writing to Socket</p>”);
// Write some test data to our socket
if(!socket_write($socket, “SOME DATA
”))
{
    echo(“<p>Write failed</p>”);
}

// Read any response from the socket
while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ))
{
    echo(“<p>Data sent was: SOME DATA<br> Response was:“ . $buffer . ”</p>”);
}
echo(“<p>Done Reading from Socket</p>”);
?>

This example client connects to the server using all the code that you have seen before. The client reads the data. If this is the first time through the loop on the first connection, then the server will send “NO DATA” back to the client. If this occurs, the client continues on. The client sends its data to the server. After the data has been sent to the server the client waits for a response. Once it receives a response it writes the response to the screen.

NOTE

You will want to edit your php.ini file to turn off notices. You can do this by adding “& ~E_NOTICE” to the error_reporting line.

NOTE

When using PHP_NORMAL_READ the line of data is considered done once the escape characters have been sent.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset