php socket 第三方库 composer require react/socket
该库针对 socket / 流 做事件监听(应该是epoll )主线程做事件循环 (reactive)所以该reactive 框架貌似只能在 linux下使用
server
<?php
require '../vendor/autoload.php';
echo "enter script\n";
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server('127.0.0.1:8080', $loop);
$socket->on('connection', function (React\Socket\ConnectionInterface $connection) {
echo "" . $connection->getRemoteAddress() . "client connected\n";
$connection->write("Hello " . $connection->getRemoteAddress() . "!\n");
$connection->write("Welcome to this amazing server!\n");
$connection->write("Here's a tip: don't say anything.\n");
$connection->on('data', function ($data) use ($connection) {
echo "" . $data . "\n";
//$connection->close();
});
});
echo "server started at 8080\n";
$loop->run();
其中$loop 就是事件循环对象
client
<?php
require '../vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$connector = new React\Socket\Connector($loop);
$connector->connect('127.0.0.1:8080')->then(function (React\Socket\ConnectionInterface $connection) use ($loop) {
echo "client connected\n";
$connection->write("Hello World!\n");
$connection->on('data', function ($data) use ($loop, $connection) {
echo "" . $data . "\n";
//$connection->close();
//$output = new React\Stream\WritableResourceStream(fopen("./client.txt", "w"),$loop);
//$output = fopen("./client.txt", "w");
//fwrite($output,$data);
//$output->write("" . $data . "\n");
while($input = fgets(STDIN, 10))
{
echo $input."\n";
$connection->write($input);
}
});
/*
$input = new React\Stream\ReadableResourceStream(STDIN,$loop);
$input->on("data",function ($data) use ($connection) {
$connection->write($data);
});*/
//$output = fopen("./client.txt", "w");
//$steam = new React\Stream\WritableResourceStream($output,$loop);
//$connection->pipe($steam);
});
$loop->run();
最亮眼的是 将文件描述符(标准输出流 文件输出流)fd 包装成一个响应式流对象 通过pipe实现管道功能 而且生命周期相同 会同时关闭。