1. 云栖社区>
  2. PHP教程>
  3. 正文

PHP Socket

作者:用户 来源:互联网 时间:2017-12-01 09:26:43

phpsocket

PHP Socket - 摘要: 本文讲的是PHP Socket, server.php <?php// 建立server端socket$tcp = getprotobyname("tcp");$socket = socket_create(AF_INET, SOCK_STREAM, $tcp);


server.php




<?php
// 建立server端socket
$tcp = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $tcp);
socket_bind($socket, '127.0.0.1', 10008); //绑定要监听的端口
socket_listen($socket); //监听端口
//初始化一个数据,和客户端通信
$buffer ="connect";
while (true) {
// 接受一个socket连接
$connection = socket_accept($socket);
if(!$connection){
echo"connect fail";
}else{
echo"Socket connectedn";
// 向客户端传递一个信息数据
if ($buffer !="") {
echo"send data to clientn";
socket_write($connection, $buffer ."n");
echo"Wrote to socketn";
} else {
echo"no data in the buffern";
}
// 从客户端取得信息
while ($data = @socket_read($connection, 1024, PHP_NORMAL_READ)) {
printf("Buffer:". $data ."n");
//取得信息给客户端一个反馈
socket_write($connection,"Information Receivedn");
}
}
socket_close($connection);
//关闭 socket
printf("Closed the socketn");
}
?>
 

client.php




<?php
// 建立客户端的socket连接
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connection = socket_connect($socket, '127.0.0.1', 10008); //连接服务器端socket
while ($buffer = @socket_read($socket, 1024, PHP_NORMAL_READ)) {
//服务端告诉客户端,自己的状态
if (preg_match("/not connect/",$buffer)) {echo"don`t connectn";break;
} else {//服务器传来信息echo"Buffer Data:". $buffer ."n";echo"Writing to Socketn";// 将客户的信息写到通道中,传给服务器端if (!socket_write($socket,"SOME DATAn")) {echo"Write failedn";}//服务器端收到信息后,给于的回应信息while ($buffer = socket_read($socket, 1024, PHP_NORMAL_READ)) {echo"sent to server: SOME DATAn response from server was:". $buffer ."n";}}
}
?>
 

以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索php socket ,以便于您获取更多的相关知识。