swoole学习笔记第三季
ps:每次PHP 运行swoole的时候 都是把代码写入内存然后执行 每次执行的都是内存里的代码 所以 每次改完以后 需要重新PHP执行 从存储中写入内存执行
以下代码就是 swoole收到的数据存入redis缓存
<?php
//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
foreach($ws->connections as $fd)
{
$ws->push($request->fd, "hello, welcome1\n");
}
//获取连接总数
echo '获取所有链接数'.count($ws->connections).'\n';
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
echo "Message: {$frame->data}\n";
//连接本地的 Redis 服务
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo "Connection to server sucessfully";
//存储数据到列表中
$redis->lpush("tutorial-list", "Redis");
$redis->lpush("tutorial-list", "Mongodb");
$redis->lpush("tutorial-list", "Mysql");
// 获取存储的数据并输出
$arList = $redis->lrange("tutorial-list", 0 ,5);
echo "Stored string in redis";
var_dump($arList);
$ws->push($frame->fd, "server: {$frame->data}");
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
如果遇到什么不懂的地方直接关注公众号留言(本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。)
作者:newmiracle
出处:https://www.cnblogs.com/newmiracle/

浙公网安备 33010602011771号