Home  >  Article  >  Backend Development  >  php中fsockopen用法实例_php技巧

php中fsockopen用法实例_php技巧

WBOY
WBOYOriginal
2016-05-16 20:26:31884browse

本文实例讲述了php中fsockopen用法。分享给大家供大家参考。

具体实现方法如下:

复制代码 代码如下:
$fp=fsockopen("127.0.0.1",80);     //打开数据流
if(!$fp)           //如果打开出错
{
  echo "unable to openn";       //输出内容
}
else            //如果成功打开
{
  fwrite($fp,"get / http/1.0rnrn");     //向数据流写入内容
  stream_set_timeout($fp,2);       //进行超时设置
  $res=fread($fp,2000);        //读取内容
  $info=stream_get_meta_data($fp);      //获取数据流报头
  fclose($fp);          //关闭数据流
  if($info['timed_out'])        //如果超时
  {
    echo 'connection timed out!';      //输出内容
  }
  else
  {
    echo $res;          //输出读取内容
  }
}
 
//实例二
 
//创建服务端
$socket=stream_socket_server("tcp://0.0.0.0:8000",$errno,$errstr);
//如果创建失败
if(!$socket)
{
  echo "$errstr ($errno)
n";
}
//如果创建成功
else
{
  //接受连接
  while($conn=stream_socket_accept($socket))
  {
    //写入数据
    fwrite($conn,'the local time is '.date('n/j/y g:i a')."n");
    //关闭连接
    fclose($conn);
  }
  //关闭socket
  fclose($socket);
}
 
//
 
$file="test.txt";       //定义文件
$fp=fopen($file,"w");      //打开数据流
if($fp)        //如果成功打开
{
  stream_set_write_buffer($fp,0);   //设置缓冲区
  fwrite($fp,$output);      //写入内容
  fclose($fp);       //关闭数据流
}

希望本文所述对大家的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn