Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
基于 reactphp 的 tcp 服务消息推送
<?php
/**
* 感谢强大的 reactphp 。
* 使用 reactphp 创建的可以限制连接数量的消息服务器
* 1. 可以群发消息
* 2. 可以客户端单对单发消息
* 3. 可以服务器对单个客户端发送消息
* usage by `composer require react/socket:^1.1`
**/
require_once __DIR__ . '/vendor/autoload.php';
use React\EventLoop\Factory;
use React\Socket\Server;
use React\Socket\ConnectionInterface;
use React\Socket\LimitingServer;
$loop = Factory::create();
$server = new Server(isset($argv[1]) ? $argv[1] : 0, $loop, array(
'tls' => array(
'local_cert' => isset($argv[2]) ? $argv[2] : (__DIR__ . '/localhost.pem')
)
));
$server = new LimitingServer($server, null);
$clients=[];
$server->on('connection', function (ConnectionInterface $client) use (&$server,&$clients) {
// whenever a new message comes in 注意此处一定要用&server &clients server 其实可以不用 此处因为基于 reactphp 官方 chatserver 脚本创建,所以暂时引用后续再优化此处的 server
$client->on('data', function ($data) use ($client, &$server,&$clients) {
echo $client->getRemoteAddress().'connected'.PHP_EOL;
$client->write($client->getRemoteAddress().'connected'."\r\n");
$clients[md5($client->getRemoteAddress())]=$client;
dump(array_keys($clients));
// remove any non-word characters (just for the demo)
$data = trim(preg_replace('/[^\w\d \.\,\-\!\?]/u', '', $data));
// ignore empty messages
if ($data === '') {
return;
}
// prefix with client IP and broadcast to all connected clients
$data = trim(parse_url($client->getRemoteAddress(), PHP_URL_HOST), '[]') . ': ' . $data . PHP_EOL;
foreach ($server->getConnections() as $connection) {
$connection->write($data);
}
});
});
$server->on('error', 'printf');
echo 'Listening on ' . $server->getAddress() . PHP_EOL;
$loop->addPeriodicTimer(1,function ()use (&$clients){
echo 'timer'.PHP_EOL;
$content = file_get_contents('a.text');
$contentArray = explode(' ',$content);
if(isset($clients[$contentArray[0]])){
echo 'runerr'.PHP_EOL;
$clients[$contentArray[0]]->write($contentArray[1].PHP_EOL);
}
});
$loop->run();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.