php socket基础知识
两个程序相互通信连接实现的数据交换,连接的一端叫socket.每一个服务创建一个socket,并且绑定一个端口,不同的端口对应不同的服务。服务端socket监听端口等待被连接,客户端socket连接发起请求.
使用socket建立一个http连接
http协议是一个基于tcp协议的应用层协议,我们可以使用socket去发送一个http请求。
简单的使用socket创建GET请求
<?php
// domain 可用的地址/协议
// type 套接字使用的类型
// protocol 协议名称
<?php
// 创建socket套接字
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// 连接http服务器
socket_connect($socket, "localhost",80);
// 发送GET请求
$buf = "GET http://localhost/helloworld.php?v=1\r\n";
$buf .= "Host:localhost\r\n";
$buf .= "User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36\r\n";
$buf .= "Connection:keep-alive\r\n";
socket_write($socket,$buf,strlen($buf)) or sprintf( "Unable to write to socket: %s", socket_strerror(socket_last_error()));
$recive = "";
while( "" !== ($read = socket_read($socket, 1024))){
$recive .= $read;
}
// 关闭请求
socket_close($socket);
// 接受内容
echo $recive;
服务端 helloworld.php代码
<?php
echo "Hello World <br />";
if(isset($_GET['v'])){
echo "Version: {$_GET['v']}";
}
php Http.php
运行结果
Hello World <br />Version: 1
使用fsockopen创建http POST请求
方法介绍
resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )
客户端脚本
<?php
// 打开socket连接资源
$fp = fsockopen("127.0.0.1",80,$errno,$errstr,5);
// 如果无法打开连接则提示失败
if(!$fp){
die("$errstr ($errno)<br />\n");
}
$data = http_build_query(array(
"username" => "liyl",
"pass" => "123456"
)
);
$out = "POST /post.php HTTP/1.1\r\n";
$out .= "Host: localhost\r\n";
$out .= "Content-Length:" .strlen($data). "\r\n";
$out .= "Content-Type:application/x-www-form-urlencoded\r\n";
$out .= "Connection: keep-alive\r\n\r\n"; // 头部与内容两个换行
$out .= $data ."\r\n\r\n"; // 结尾两个换行
fwrite($fp,$out); // 写入流
$ret = "";
// while( "" !== ($read = fread($fp,8192)) ){
// $ret .= $read;
// }
while(!feof($fp)){
$ret .= fgets($fp,1280);
}
fclose($fp);
echo $ret;
服务端脚本
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
header("Content-Type:text/css;charset=UTF-8;");
echo "recive:";
print_r($_POST);
exit;
}
?>
<form action="" method="POST">
<input type="hidden" name="test" value="test">
<button submit>GO</button>
</form>
php HttpPost.php
运行结果
HTTP/1.1 200 OK
Date: Sat, 30 Apr 2016 07:03:52 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.6.20
Content-Length: 61
Connection: close
Content-Type: text/html; charset=UTF-8
recive:Array
(
[username] => liyl
[pass] => 123456
)
先打开了一个网络连接,然后发送了报头和报文.同时将响应的内容追加在这个网络连接中
小结
作为php语言本身来说,它更加适合做一个socket客户端,服务端的编写我们更愿意交给c语言,java语言。原因在于这些语言有更好的解决并发的特性
只要我们遵循一定的网络协议.就可以实现不同程序的数据通信
网络编程是一门很大的学问