首页 > 代码库 > socket 发送请求

socket 发送请求

 

socket方式:

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);//socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec"=>20, "usec"=>0));socket_connect($socket, ‘www.baidu.com‘, 80);//里面的换行代表 \r\n 注意拷贝的代码后面可能有空格$http = <<<eofGET / HTTP/1.0Accept: */*User-Agent: Lowell-AgentHost: www.baidu.comConnection: Closeeof;socket_write($socket, $http, strlen($http));while($str = socket_read($socket, 1024)){    echo $str;}socket_close($socket);

 

fsockopen方式:

$fp = fsockopen("www.baidu.com", 80, $errno, $errstr, 30);if (!$fp) {    echo "$errstr ($errno)<br />\n";} else {    $out = "GET / HTTP/1.1\r\n";    $out .= "Host: www.baidu.com\r\n";    $out .= "Connection: Close\r\n\r\n";    fwrite($fp, $http);    while (!feof($fp)) {        echo fgets($fp, 128);    }    fclose($fp);}

 

原始socket方式:

$fp = stream_socket_client("tcp://www.baidu.com:80", $errno, $errstr, 30);if (!$fp) {    echo "$errstr ($errno)<br />\n";} else {        $http = <<<eofGET / HTTP/1.0Accept: */*User-Agent: Lowell-AgentHost: www.baidu.comConnection: Closeeof;        fwrite($fp, $http);    while (!feof($fp)) {        echo fgets($fp, 1024);    }    fclose($fp);}

 

socket 发送请求