php聊天室(swoole/redis)

环境Mac OS 10.10
php环境 xampp
PHP7.0安装swoole/redis扩展
安装php扩展 php安装扩展(swoole/redis)


swooleServer.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 "客户端{$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);//循环广播

}

});

$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代码贴不进去只能截图了)

php聊天室(swoole/redis)_第1张图片

启动apache服务

命令行执行./redis-server启动 redis服务端//在redis目录下的src目录下执行redis-server ,./redis-cli 启动redis客户端

cd /Applications/XAMPP/xamppfiles/htdocs/swooleDemo//进入php目录下

/Applications/XAMPP/xamppfiles/bin/php -c /Applications/XAMPP/xamppfiles/etc/php.ini swooleServer.php//启动swoole服务端,-c 指定php.ini配置文件运行php

在浏览器里访问  client.html

PS:若访问apache自定义目录下访问网页出错,403 Access Forbidden,访问权限受限

在httpd.conf修改配置

Options FollowSymLinks

AllowOverride None

Order deny,allow

# denyfromall    # 原先的默认设置

Allowfromall    # 改成 Allow 问题解决

修改完仍然无法访问

在终端中执行chmod -R 777 /Applications/XAMPP/xamppfiles/htdocs/swooleDemo


END!

你可能感兴趣的:(php聊天室(swoole/redis))