基于swoole實現(xiàn)多人聊天室
本文實例為大家分享了swoole創(chuàng)建多人多房間聊天室的具體代碼,供大家參考,具體內(nèi)容如下
核心的swoole代碼
基本的cs(client-sercer)結(jié)構(gòu)不變,這里利用的是redis的哈希和set來儲存和分組;從而達到了分組,統(tǒng)計,定時推送等功能;最后利用onclose事件來剔除斷開的連接,全部代碼如下:(沒做前端,就不展示了)
核心的swoole ws.php
<?php
namespace app\common;
require_once 'Predis.php';
require_once 'Task.php';
/**
* socket面向?qū)ο蟮木幾g
*/
class Ws
{
CONST HOST='0.0.0.0';
CONST PORT='9501';
public $ws=null;
public $getmsg=null;
public $server=null;
public function __construct()
{
$this->ws=new \swoole_websocket_server(self::HOST,self::PORT);
$this->ws->set([
//啟動task必須要設(shè)置其數(shù)量
'worker_num' => 4,
'task_worker_num' => 2,
// 'heartbeat_check_interval' => 5,
// 'heartbeat_idle_time' => 10,
]);
//監(jiān)聽新端口
$this->server=$this->ws->listen("127.0.0.1", 9502, SWOOLE_SOCK_TCP);
//關(guān)閉websocket模式
$this->server->set([
'open_websocket_protocol' => false,
]);
$this->ws->on("start", [$this, 'onStart']);
$this->ws->on('open',[$this,'onopen']);
$this->server->on("receive", [$this, 'onReceive']);
$this->ws->on('task',[$this,'onTask']);
$this->ws->on('finish',[$this,'onFinish']);
$this->ws->on('message',[$this,'onmessage']);
$this->ws->on('close',[$this,'onclose']);
$this->server->on("close", [$this, 'oncloses']);
$this->ws->start();
}
//監(jiān)聽數(shù)據(jù)接收事件
public function onReceive($serv, $fd, $from_id, $data)
{
$shuju=json_decode($data,ture);
// print_r($shuju).PHP_EOL;
if (empty($shuju['data'])) {
$this->ws->push(Predis::getInstance()->get('fd'), $data);
}else{
if (empty($shuju['msg'])) {
//執(zhí)行異步任務(wù)
$this->ws->task($shuju);
}else{
$push_arr=Predis::getInstance()->hvals($shuju['data']);
// echo "集群是:".print_r($push_arr);
foreach ($push_arr as $v) {
$this->ws->push($v, $shuju['msg']);
}
}
}
}
/**
* 設(shè)置進程名,為后續(xù)平滑重啟進程
* @param $server
*/
public function onStart($server) {
swoole_set_process_name("live_master");
}
/**
監(jiān)聽開啟事件的回調(diào)
*/
public function onopen($server, $request)
{
print_r("這時的fd是:",$request->fd);
Predis::getInstance()->set('fd',$request->fd);
}
/**
監(jiān)聽接收事件的回調(diào)
*/
public function onmessage($server, $frame)
{
$server->push($frame->fd, "{$frame->data}");
}
/**
監(jiān)聽關(guān)閉事件的回調(diào)
*/
public function onclose($ser, $fd)
{
print_r("你好,我的{$fd}\n");
//退出并刪除多余的分組fd
$group=Predis::getInstance()->sMembers('group');
foreach ($group as $v) {
$fangjian=Predis::getInstance()->hgetall($v);
foreach ($fangjian as $k => $vv) {
if ($fd == $vv) {
Predis::getInstance()->hdel($v,$k);
}
}
}
}
public function oncloses($ser, $fd)
{
print_r("這個是client{$fd}\n");
}
/**
* $serv 服務(wù)
* $task_id 任務(wù)ID,由swoole擴展內(nèi)自動生成,用于區(qū)分不同的任務(wù)
* $src_worker_id $task_id和$src_worker_id組合起來才是全局唯一的,不同的worker進程投遞的任務(wù)ID可能會有相同
* $data 是任務(wù)的內(nèi)容
*/
public function onTask($serv,$task_id,$src_worker_id,$data)
{
//引入任務(wù)
$obj = new Task;
$method = $data['data'];
$arr = $data['arr'];
//發(fā)布具體的任務(wù)
$flag = $obj->$method($arr, $serv);
return $flag; // 告訴worker
}
/**
* $task_id 是任務(wù)的ID
* $data 是任務(wù)處理的結(jié)果內(nèi)容
*/
public function onFinish($serv,$task_id,$data)
{
print_r($data).'/n';
}
}
new Ws();
分發(fā)任務(wù)task.php
<?php
/**
* 代表的是 swoole里面 后續(xù) 所有 task異步 任務(wù) 都放這里來
* Date: 18/3/27
* Time: 上午1:20
*/
namespace app\common;
// include 'Predis.php';
class Task {
//異步創(chuàng)建房間
public function chuangjian($data,$serv)
{
$time=$data['time']*1000;
swoole_timer_after($time, function() use($data){
//創(chuàng)建房間(修改拍賣商品狀態(tài))
self::post("https://code.77wx.cn/index/index/in");
});
}
//進入房間并緩存信息
public function jingru($data,$serv)
{
$fd=Predis::getInstance()->get('fd');
//加入分組
Predis::getInstance()->hset($data['name'],$data['uid'],$fd);
//加入組集合
Predis::getInstance()->sadd('group',$data['name']);
}
public function post($url,$params=false,$ispost=0)
{
$httpInfo = array();
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
if( $ispost )
{
curl_setopt( $ch , CURLOPT_POST , true );
curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
curl_setopt( $ch , CURLOPT_URL , $url );
}
else
{
if($params){
curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
}else{
curl_setopt( $ch , CURLOPT_URL , $url);
}
}
//執(zhí)行
$response = curl_exec( $ch );
if ($response === FALSE) {
//echo "cURL Error: " . curl_error($ch);
return false;
}
$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
//關(guān)閉url請求
curl_close( $ch );
return json_decode($response,1);
}
}
客戶端 client.php
<?php
namespace app\common;
class Client
{
public $msg='';
public $data=[];
public function lianjie(){
$cli = new \swoole_client(SWOOLE_SOCK_TCP);
//判斷連接狀態(tài)(同步連接模式)
$res=$cli->connect('127.0.0.1', 9502);
if (empty($res)) {
return "連接失敗";
}
if (!empty($this->data)) {
//發(fā)送消息給server
$rel=$cli->send(json_encode($this->data));
}else{
//發(fā)送消息給server
$rel=$cli->send($this->msg);
}
if (!empty($rel)) {
return $rel;
}else{
return flash;
}
}
}
控制器index.php
<?php
namespace app\index\controller;
use app\common\Client;
use app\common\Predis;
use app\common\Sql;
use app\index\model\User;
class Index
{
//創(chuàng)建房間(添加拍賣倒計時)
public function chuangjian()
{
$data['time']=input("time");
$data['id']=input("id");
$cli = new Client();
$cli->data = [
'data' => 'chuangjian',
'arr' => $data
];
return $cli->lianjie();
}
//點擊添加哈希(進入房間)
public function jingru()
{
$data['name']=input("name");
$data['uid']=input("uid");
$cli = new Client();
$cli->data = [
'data' => 'jingru',
'arr' => $data
];
return $cli->lianjie();
}
//本房間推送(出價格成功并推送)
public function pushfan()
{
$data['fan']=input("fan");
$cli = new Client();
$cli->data = [
'data' => $data['fan'],
'msg' => "恭喜用戶111,喜當?shù)?!!!"
];
return $cli->lianjie();
}
//時間結(jié)束并指定推送
public function zhiding()
{
$data['fan']=input("fan");
$cli = new Client();
$cli->data = [
'data' => $data['fan'],
'msg' => "恭喜用戶111,喜當?shù)?!!!"
];
return $cli->lianjie();
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Zend Framework入門教程之Zend_View組件用法示例
這篇文章主要介紹了Zend Framework中Zend_View組件用法,結(jié)合實例形式簡單分析了Zend_View組件視圖操作的相關(guān)技巧與注意事項,需要的朋友可以參考下2016-12-12
如何使用PHP Embed SAPI實現(xiàn)Opcodes查看器
這篇文章主要介紹了如何使用PHP Embed SAPI實現(xiàn)Opcodes查看器的相關(guān)資料,需要的朋友可以參考下2015-11-11
Yii2隱藏frontend/web和backend/web的方法
這篇文章主要介紹了Yii2隱藏frontend/web和backend/web的方法,需要的朋友可以參考下2015-12-12
windows中為php安裝mongodb與memcache
這篇文章主要介紹了windows中為php安裝mongodb與memcache的方法,十分的詳盡,需要的朋友可以參考下2015-01-01
php如何實現(xiàn)數(shù)據(jù)庫的備份和恢復(fù)
這篇文章主要介紹了php如何實現(xiàn)數(shù)據(jù)庫的備份和恢復(fù),本文給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11

