浅析PHP Socket技术

  phpsocketSocket位于TCP/IP协议的传输控制协议,提供客户-服务器模式的异步通信,即客户向服务器发出服务请求,服务器接收到请求后,提供相应的反馈或服务!我练习了一个最基本的例子:

  使用并发起一个阻塞式(block)连接,即服务器如果不返回数据流,则一直保持连接状态,一旦有数据流传入,取得内容后就立即断开连接。代码如下:

  

复制代码 代码如下:

  <?php

  $host = www.sohu.com; //这个地址随便,用新浪的也行,主要是测试用,哪个无所谓

  $page = "/index.html";

  $port = 80;

  $request = "GET $page HTTP/1.1\r\n";

  $request .= "Host: $host\r\n";

  //$request .= "Referer:$host\r\n";

  $request .= "Connection: close\r\n\r\n";

  //允许连接的超时时间为1.5秒

  $connectionTimeout = 1.5;

  //允许远程服务器2秒钟内完成回应

  $responseTimeout = 2;

  //建立一个socket连接

  $fp = fsockopen($host, $port, $errno, $errstr, $connectionTimeout);

  if (!$fp) {

  throw new Exception("Connection to $hostfailed:$errstr");

  } else {

  stream_set_blocking($fp, true);

  stream_set_timeout($fp, $responseTimeout);

  }

  //发送请求字符串

  fwrite($fp, $request);

  //取得返回的数据流内容

  $content = stream_get_contents($fp);

  echo $content;

  $meta = stream_get_meta_data($fp);

  if ($meta['timed_out']) {

  throw new Exception("Responsefrom web services server timed out.");

  }

  //关闭Socket连接

  fclose($fp);

  ?>