PHP Socket Programming Tutorial

Every programming language enable to use socket programming to provide the communication mechanism between two processes on the same or different machine. PHP is the one of the programming language that able to use the socket. A Socket is mostly used in a client-server application framework. There have many application-level protocols like FTP, HTTP, and HTTPS to make use of sockets to establish connection between client and server.

Create a PHP file

Open your PHP editor and create a php file name “server”. Below is the server.php code and insert the following code.

<?php

set_time_limit(0);

$ip = '127.0.0.1';
$port = 1935;

/*
 +-------------------------------
 *    @socketcommunicateprocess
 +-------------------------------
 *    @socket_create
 *    @socket_bind
 *    @socket_listen
 *    @socket_accept
 *    @socket_read
 *    @socket_write
 *    @socket_close
 +--------------------------------
 */

if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {
    echo "socket_create() Fail to create:".socket_strerror($sock)."\n";
}

if(($ret = socket_bind($sock,$ip,$port)) < 0) {
    echo "socket_bind() Fail to bind:".socket_strerror($ret)."\n";
}

if(($ret = socket_listen($sock,4)) < 0) {
    echo "socket_listen() Fail to listen:".socket_strerror($ret)."\n";
}

$count = 0;

do {
    if (($msgsock = socket_accept($sock)) < 0) {
        echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
        break;
    } else {

        $msg ="Success receive from client!\n";
        socket_write($msgsock, $msg, strlen($msg));

        echo "Success\n";
        $buf = socket_read($msgsock,8192);


        $talkback = "Received Message:$buf\n";
        echo $talkback;

        if(++$count >= 5){
            break;
        };


    }
    //echo $buf;
    socket_close($msgsock);

} while (true);

socket_close($sock);
?>

Open command prompt

Open your cmd and type php (path)/(your-file-name). Way to open cmd : search cmd in the bottom bar.

php socket programming

Edit client.php file

After that create one more php file name “client” and insert the below code.

<?php
error_reporting(E_ALL);
set_time_limit(0);
echo "<h2>TCP/IP Connection</h2>\n";

$port = 1935;
$ip = "127.0.0.1";

/*
 +-------------------------------
 *    @socketconectionprocess
 +-------------------------------
 *    @socket_create
 *    @socket_connect
 *    @socket_write
 *    @socket_read
 *    @socket_close
 +--------------------------------
 */

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
    echo "socket_create() failed. reason: " . socket_strerror($socket) . "\n";
}else {
    echo "OK.\n";
}

echo "Try to connect '$ip' Port '$port'...\n";
$result = socket_connect($socket, $ip, $port);
if ($result < 0) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
}else {
    echo "Connect OK\n";
}

$in = "Testing\r\n";
$out = '';

if(!socket_write($socket, $in, strlen($in))) {
    echo "socket_write() failed. reason: " . socket_strerror($socket) . "\n";
}else {
    echo "Send Message to Server Successfully!\n";
    echo "Send Information:<font color='red'>$in</font> <br>";
}

while($out = socket_read($socket, 8192)) {
    echo "Receive Server Return Message Successfully!\n";
    echo "Received Message:",$out;
}


echo "Turn Off Socket...\n";
socket_close($socket);
echo "Turn Off OK\n";
?>

Open second command prompt

Open another command prompt,  insert the client.php path. Below are example.

Check client respond

After that, you will see the server(1st command prompt) respond from the client(2nd command prompt).

(PHP Socket Programming)

Source Code

(Visited 11,513 times, 1 visits today)
Advertisements

Yong Loon Ng

Ng Yong Loon, better known as Kristofer is a software engineer and computer scientist who doubles up as an entrepreneur.

You may also like...

6 Responses

  1. cool says:

    I want to apply same on browser .. please help

  2. Femina F says:

    <?php
    error_reporting(E_ALL);
    set_time_limit(0);
    echo "TCP/IP Connection\n”;

    $port = 1935;
    $ip = “127.0.0.1”;

    /*
    +——————————-
    * @socketconectionprocess
    +——————————-
    * @socket_create
    * @socket_connect
    * @socket_write
    * @socket_read
    * @socket_close
    +——————————–
    */

    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket < 0) {
    echo "socket_create() failed. reason: " . socket_strerror($socket) . "\n";
    }else {
    echo "OK.\n";
    }

    echo "Try to connect '$ip' Port '$port'…\n";
    $result = socket_connect($socket, $ip, $port);
    if ($result < 0) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
    }else {
    echo "Connect OK\n";
    }

    $in = "Testing\r\n";
    $out = '';

    if(!socket_write($socket, $in, strlen($in))) {
    echo "socket_write() failed. reason: " . socket_strerror($socket) . "\n";
    }else {
    echo "Send Message to Server Successfully!\n";
    echo "Send Information:$in “;
    }

    while($out = socket_read($socket, 8192)) {
    echo “Receive Server Return Message Successfully!\n”;
    echo “Received Message:”,$out;
    }

    echo “Turn Off Socket…\n”;
    socket_close($socket);
    echo “Turn Off OK\n”;
    ?>

  3. Yas says:

    May you explain the server code?
    Thanks

  4. Some people alternatively pay a lot money at one time to raise the probability of profitable.
    The system the place betting money is thru your financial institution is secure
    to work with, and the transaction is at all times between your account and
    the Ladbrokes. Easy system described in steps. Many are simple folks
    simply struggling to get by. This guide supplies all the info it’s essential to get into the sport.
    However the factor is that to extend your probabilities of
    profitable, you need to put a guess daily. As a substitute, you are
    able to get all the data you need from that same site.
    As long because the owner of the Bitcoin looks after it properly using a excessive-safety
    wallet and two-issue authentication, it will likely be extraordinarily difficult for anybody else to get entry
    to their funds. At any level, nonetheless, the bookie can bounce in and make changes to the
    traces that can be found to his players if knows he can be getting heavy one
    sided action.

    In case you are one of those individuals who doesnt like cats, Im sorry to hear that.
    For the above example, it might appear to be -7.5 (-110).
    Other gamers can legally purchase Mega Millions Lottery tickets on-line by the lottery agent you
    see mentioned above. As an example, MEGA Tens
    of millions is a multi-state lottery and it operates in 11 states.
    As an illustration, you would not want to pick simply any race horse in hopes of successful a guess.

    5. Wager on sports activities by inserting your wager. Once you click on the sport of your selecting make sure you bookmark the page so you’ll at all times have probably the
    most present and updated sports activities betting odds at your disposal.

    On this method, you might select a low quantity from the given set resembling 1-50 like 1.
    Some profitable numbers have two consecutive numerals,
    though not all the time. After which with the time you saved do something more productive than you would have accomplished acting
    like a poor individual.

  5. An impressive share! I’ve just forwarded this onto a colleague who had been doing a little homework
    on this. And he actually ordered me breakfast simply because I stumbled upon it for him…
    lol. So let me reword this…. Thanks for the meal!!
    But yeah, thanks for spending the time to talk about this topic here on your internet site.

Leave a Reply

Your email address will not be published. Required fields are marked *