websockt聊天

服务端

use workerman\Worker;
require dirname(__DIR__).'\Autoloader.php';
// 心跳间隔25秒
// define('HEARTBEAT_TIME', 25);


// 创建一个Worker监听9001端口,不使用任何应用层协议
$ws = new Worker("websocket://172.18.10.179:9001");


// 启动4个进程对外提供服务
$ws->count = 1;


// 用来保存uid到connection的映射(uid是用户id或者客户端唯一标识)
$worker->uidConnections = array();
$worker->usernames = array();




// 当客户端发来数据时
$ws->onMessage = function($connection, $data)
{
$getMsg = json_decode($data,true); //传递参数
//发送消息类型 login all toid
$type = isset($getMsg['type'])?$getMsg['type']:"";
$uid = isset($getMsg['username'])?$getMsg['username']:""; //formid
$message =isset($getMsg['message'])? $getMsg['message']:""; //msg
$connection->lastMessageTime = time(); //time
global $worker;

// 登录
if($type == "login")
{
if(!isset($connection->uid))
{
$connection->uid = $uid;
$worker->uidConnections[$uid] = $connection;
$worker->usernames[$uid] = $uid;
}
$result = array(
'msg' => "欢迎".$uid."进入聊天室!",
'data' => $worker->usernames
);
broadcast(json_encode($result));
} else if($type == "all") { // 广播
$result = array(
'msg' => $connection->uid."对大家说:".$message,
);
var_dump($result);
broadcast(json_encode($result));
} else { // 给特定uid发送
sendMessageByUid($connection->uid, $type, $message); 
}

};


$ws->onClose = function($connection){
global $worker;
    if(isset($connection->uid))
    {
        unset($worker->uidConnections[$connection->uid]);
        unset($worker->usernames[$connection->uid]);
    }
};


// 向所有验证的用户推送数据
function broadcast($message)
{
   global $worker;
   if(count($worker->uidConnections) != 0)
   {
  foreach($worker->uidConnections as $connection)
  {
       $connection->send($message);
  }
   }
}


// 针对uid推送数据
function sendMessageByUid($fromid, $tid, $message)
{
    global $worker;
    if(isset($worker->uidConnections[$tid]))
    {
    $selfconnection = $worker->uidConnections[$fromid];
        $connection = $worker->uidConnections[$tid];
        $result = array(
'msg' => $fromid."对".$tid."说:".$message,
);
        $connection->send(json_encode($result));
        $selfconnection->send(json_encode($result));
    }
}


$worker->onClose = function($connection)
{
global $worker;
    unset($worker->uidConnections[$connection->uid]);
};




// 运行worker
Worker::runAll();


客户端登录





login




请输入用户名:








客户端聊天





client









if(!isset($_POST['username']))
{
header("Location:login.php");
}
?>






所有用户:


       

       
   







你可能感兴趣的:(PHP)