socket client

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
seesoe
Forum Newbie
Posts: 2
Joined: Thu Jan 15, 2009 12:18 am

socket client

Post by seesoe »

hello, im trying to make a simple php socket client that will send a small string of data to a server

heres what i have

Code: Select all

$host      = "server ip";
$port      = 4321; // nat opened port
$timeout = 6000;
 
$sk = fsockopen($host,$port,$errnum,$errstr,$timeout);
 
if (!is_resource($sk) || $errnum) {
    exit("connection fail: ".$errnum." ".$errstr);
} else {
stream_set_blocking($sk, false);
    fwrite($sk, "hello world");
    $dati = "";
    while (!feof($sk)) {
        $chunk = fgets ($sk, 1024);
        if ($chunk !== False) {
            $dati.= $chunk;
            break;
        }
    }
    echo $dati;
}
 
fclose($sk);  
i was able to get things running locally, but im trying to make this work with the php client be run on a remote server, but i keep getting the same issue of getting an instant disconnected message from my server and client times out. i have port 4321 on the router open to the socket server program. my webhost's php info says they allow sockets
seesoe
Forum Newbie
Posts: 2
Joined: Thu Jan 15, 2009 12:18 am

Re: socket client

Post by seesoe »

i am also using this with the same results

Code: Select all

<?php
error_reporting(E_ALL);
 
echo "<h2>TCP/IP Connection</h2>\n";
 
/* Get the port for the WWW service. */
$service_port = 4321;
 
/* Get the IP address for the target host. */
$address = gethostbyname('server domain');
 
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}
 
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}
 
stream_set_blocking($socket, false);
$in = "Hello World!\r\n";
$out = '';
 
echo "Sending request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";
 
echo "Reading response:\n\n";
while ($chunk = socket_read($socket, 2048)) {
        if ($chunk !== False) {
            $out.= $chunk;
            break;
        }
}
        echo $out;
 
echo "Closing socket...";
socket_close($socket);
echo "OK.";
?>
Post Reply