PHP中的网络编程 -- Socket篇

来源:互联网 发布:黑暗之魂3卡顿优化补丁 编辑:程序博客网 时间:2024/05/22 14:11

作为WEB应用,网络编程是必不可少的。在实际的应用中,所需要网络编程的是

1.HTTP协议的请求,比如上传、下载什么的;

   2.就是TCP/IP层的操作。比如,公司内部的协议解析。再往底层就基本没有了。

 

对于TCP/IP层的操作,在我们这边有内部的通信协议。然后,在这一层的网络通信基本都是很底层的。所以,基本都是使用pack, unpack以及位移等操作,不过,最重要的就是socket的编程。另外,还有文件的操作,比如使用到fwritefread.在某些地方还以使用fget, fput函数。简单的介绍下sock编程:

 

PHPSocket基本上使用fsocketopen()socket_*函数集。简单的使用如下:

<?php$host='www.sina.com.cn'; $page='/index.html';$fp = fsockopen($host, 80, $errno, $errdesc) or die('connect to$host failed');$request = "GET $page HTTP/1.1 \r\n";$request .= "HOST: $host\r\n";$request .="Referer: $host\r\n"; fpus($fp, $request);while(!feof($fp)){$page[] = fgets($fp, 1024);} fcolse($fp); echo "服务器返回".(count($page))."行";?>

这个例子就是建立一个短连接。下面展示如何发起一个阻塞式(block)连接,即服务器如果不返回数据流,则一直保持连接状态,一但有数据流传入,取得内容后就立即断开连接。

<?php    $serverDomain = 'www.sohu.com';    $port = 80;    $request = 'GET /index.html HTTP/1.0\r\n';    $request .= "Host:$serverDomain\\r\\n";    $request .= 'Connection: close\r\n\r\n';     $connectTimeout = 1.5;    $responseTimeout = 2;     $conn = fsockopen($serverDomain, $port,$errno, $errstr, $connectTimeout);    if(!$conn){        throw new Exception('unable connect.');    }else{        stream_set_blocking($conn, TRUE);        stream_set_timeout($conn,$responseTimeout);    }    fwrite($conn, $request);     $response = stream_get_contents($conn);     echo $response;     fclose($conn);?>

原创粉丝点击