关于php的socket
最近在学php的socket,想通过一个功能的实现检验我对socket的理解:
1、client端发送数据到服务器端
2、server端接收client发送过来的数据,并会送一个响应给client端
3、client端显示server端发过来的响应信息
以下是代码
server.php:
// Set up our socket
$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
socket_bind($socket, 'localhost', 1234);
socket_listen($socket);
// Initialize the buffer
$buffer = "NO DATA";
while(true) {
// Accept any connections coming in on this socket
$connection = socket_accept($socket);
printf("Socket connected\r\n");
// Check to see if there is anything in the buffer
$buffer=socket_read($connection, 2048, PHP_NORMAL_READ);
echo "recived from client ".$buffer;
$ResponseToClient=$buffer." is handled by server!\n";
socket_write($connection, $ResponseToClient);
echo "response to client!\n ";
}
?>
client.php:
// Create the socket and connect
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connection = socket_connect($socket,'localhost', 65500);
$i=0;
$s=0;
while(true)
{
echo "sending data".$i++."\n";
$SendDataToServer=socket_write($socket, "server".$s++);
$ResponseFromServer=socket_read($socket, 2048, PHP_NORMAL_READ);
echo "received".$ResponseFromServer."from server \n";
}
?>
问题是:client端只显示sending data0
而server端只显示Socket connected
其他什么也不显示,没有达到我预想的client不断发送数据,server端不断处理数据并返回给client的目的,请高手指教下,万分感谢
socket
PHP
分享到:
------解决方案--------------------没有需求干嘛弄这个?
不过可以给你个早年写的测试例
服务端
// Server
// 设置错误处理
error_reporting (E_ALL);
// 设置运行时间
set_time_limit (0);
// 起用缓冲
ob_implicit_flush ();
$ip = "127.0.0.1"; // IP地址
$port = 1000; // 端口号
$socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP); // 创建一个SOCKET
if ($socket)
echo "socket_create() successed!\n";
else
echo "socket_create() failed:".socket_strerror ($socket)."\n";
$bind = socket_bind ($socket, $ip, $port); // 绑定一个SOCKET
if ($bind)
echo "socket_bind() successed!\n";
else
echo "socket_bind() failed:".socket_strerror ($bind)."\n";
$listen = socket_listen ($socket); // 间听SOCKET
if ($listen)