環(huán)境Mac OS 10.10
php環(huán)境 xampp
PHP7.0安裝swoole/redis擴(kuò)展
安裝php擴(kuò)展?php安裝擴(kuò)展(swoole/redis)
swooleServer.php
<?php
$redis = new redis();$result = $redis->connect("127.0.0.1", 6379);
$server = new swoole_websocket_server("0.0.0.0", 9501);
$server->on('open', function (swoole_websocket_server $server, $request) {
global $redis;
$nfd = $request->fd;
echo "客戶端{(lán)$nfd}成功接入\n";
$redis->hset("User",$nfd,$nfd);//保存客戶端ID
$users = $redis->hvals("User");
var_dump($users);
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
global $redis;
$data = $frame->data;
$fd = $frame->fd;
echo "{$fd}:{$data}\n";
$users = $redis->hvals("User");//取回所有用戶
var_dump($users);
foreach ($users as $u)
{
$server->push($u , $data);//循環(huán)廣播
}
});
$server->on('close', function ($ser, $fd) {
global $redis;
$redis->hdel("User",$fd);
$users = $redis->hvals("User");
var_dump($users);
echo "client {$fd} closed\n";
});
$server->start();
?>
client.html (ps:簡書編輯器無力吐槽佩研,貼幾個html代碼貼不進(jìn)去只能截圖了)
啟動apache服務(wù)
命令行執(zhí)行./redis-server啟動 redis服務(wù)端//在redis目錄下的src目錄下執(zhí)行redis-server 氢妈,./redis-cli 啟動redis客戶端
cd?/Applications/XAMPP/xamppfiles/htdocs/swooleDemo//進(jìn)入php目錄下
/Applications/XAMPP/xamppfiles/bin/php -c /Applications/XAMPP/xamppfiles/etc/php.ini swooleServer.php//啟動swoole服務(wù)端玩般,-c 指定php.ini配置文件運行php
在瀏覽器里訪問 ?client.html
PS:若訪問apache自定義目錄下訪問網(wǎng)頁出錯,403?Access Forbidden,訪問權(quán)限受限
在httpd.conf修改配置
Options FollowSymLinks
AllowOverride None
Order deny,allow
# denyfromall? ? # 原先的默認(rèn)設(shè)置
Allowfromall? ? # 改成 Allow 問題解決
修改完仍然無法訪問
在終端中執(zhí)行chmod -R 777 /Applications/XAMPP/xamppfiles/htdocs/swooleDemo
END!