【www.gdgbn.com--php常用代码】

$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);       //关闭数据流
}

本文来源:http://www.gdgbn.com/jiaocheng/28371/