Demo entry 3539910

Socket

   

Submitted by anonymous on Jan 11, 2016 at 09:19
Language: PHP. Code size: 2.7 kB.

#!/usr/bin/php
<?PHP
/**
* phpCallApi TEST.
* socket 
*
* @Author: 고범석 (simpleguru@mezzomedia.com)
* @Date: 2015. 12. 14.
*/

set_time_limit (0); 

//Reduce errors
error_reporting(~E_WARNING);

//ssp lists
$adApiUrl = array(
			'http://218.49.170.229:8083/dsp_test/a.php',
			'http://218.49.170.229:8083/dsp_test/b.php',
			'http://218.49.170.229:8083/dsp_test/c.php',
			'http://218.49.170.229:8083/dsp_test/d.php',
			'http://218.49.170.229:8083/dsp_test/e.php'
			);

//Create a UDP socket
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}
 
// Bind the source address
if( !socket_bind($sock, "127.0.0.1" , 10000) )
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     
    die("Could not bind socket : [$errorcode] $errormsg \n");
}

//Do some communication, this loop can handle multiple clients
while(1)
{

    //Receive some data
    $r = socket_recvfrom($sock, $buf, 2048, 0, $remote_ip, $remote_port);
	$buf = trim($buf);

	$max_proc_count = 5;
	$data = array();
	for ($i=0; $i<$max_proc_count; $i++) {
		$data[] = multi_tasking($i);
	} 
	$xml = simplexml_load_string($data[0]);
	$jsonData = json_encode($xml);   	
	$output = preg_replace("[ \t\n\r]","",$jsonData).chr(0);
	//parse Data Start
	
	//parse Data End

    //Send back the cData to the client
    socket_sendto($sock, $output, 2048 , 0 , $remote_ip , $remote_port);
}
 
socket_close($sock);

//Call ssp data from servers
function CallAPI($method, $url, $data = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_TIMEOUT, 0.5);
    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}

//Fork process
function multi_tasking($arg)
{
	$pid = pcntl_fork();
	if ($pid == 0) {
		$cData = '';
		global $adApiUrl;
		$cData = CallAPI('GET',$adApiUrl[$arg]);
        return $cData;
		exit;
    } else if( $pid == -1) {
        echo '[ERROR] could not fork'."\n";
        exit;
    }else{

	}
}
?>

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).