Diptopol Dam
Diptopol Dam

Reputation: 815

socket connection code of php

I am writing a simple php socket code.
Here is my code

 <?php

    $address="127.0.0.1";
    $port=9875;
    echo "I am here";

    if(false==($socket=  socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
    {
        echo "could not create socket";
    }
    socket_bind($socket, $address, $port) or die ("could not bind socket");
    socket_listen($socket);
    if(($client=socket_accept($socket)))
        echo "client is here";

    ?>

when I run this program my browser only shows waiting for localhost.
Is there any problem in my code?
I am using xammp 1.7.4 .
Another thing I want to know if I want to get a HTTP or FTP request do I have change only the port number?

Upvotes: 1

Views: 20778

Answers (2)

AjayR
AjayR

Reputation: 4179

That is the expected behaviour of waiting. The program you have written is a socket server which is ready to listen to the connection with the specified port, until then it will wait.

You can create a client who connects so that you will see the response "Client is here". The client can be any programming language including PHP.

Below is a sample code in PHP (I didn't verify it).

$fp = stream_socket_client("127.0.0.1:9875", $errno, $errstr);

if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
   // Handle code here for reading/writing
}

You can check this link for sample client code in PHP.

EDIT

$host = "127.0.0.1";
$port = 9875;
$timeout = 30;
$sk = fsockopen($host, $port, $errnum, $errstr, $timeout);
if (!is_resource($sk)) {
    exit("connection fail: " . $errnum . " " . $errstr);
} else {
    echo "Connected";
}

Upvotes: 3

AjayR
AjayR

Reputation: 4179

I verified the code and tested in my system and it works correctly. Showing as "client is here" after running the client.

File Name: server.php

<?php
    $address="127.0.0.1";
    $port=9875;
    echo "I am here";
    set_time_limit (0); 
    if(false==($socket=  socket_create(AF_INET,SOCK_STREAM, SOL_TCP)))
    {
        echo "could not create socket";
    }
    socket_bind($socket, $address, $port) or die ("could not bind socket");
    socket_listen($socket);
    if(($client=socket_accept($socket)))
        echo "client is here";

    socket_close($socket); 
    ?>

First run the server.php file.

File: client.php

<?php
$host="127.0.0.1" ;
$port=9875;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
    exit("connection fail: ".$errnum." ".$errstr) ;
} else {

    echo "Connected";
    }
?>

Now run the client.php

Your output should be like this (as I got in my system)

I am hereclient is here

If not, make sure your firewall is not blocking the request. Temporarily disable antivirus if you have one.

Upvotes: 6

Related Questions