swoole实现发送聊天消息 (单发和群发)

一、服务端

set(array(
    'heartbeat_check_interval' =>600,   检查心里的间隔
    'heartbeat_idle_time' =>600    //最大心跳间隔
));

$server->on('open', function ($server, $request) {
    $GLOBALS['fd'][$request->fd]['id']=$request->fd;
    echo '欢迎登录,你的id='.$request->fd;
});
$server->on('message', function ($server, $request) {
    $resut = json_decode($request->data);
    $t_id  = $resut[0];
    $msg = $resut[1];
    if(is_numeric($t_id)){  //单发
        $num = 0;
        foreach ($server->connections as $conn){
            if($conn ==$t_id ){  //防止要发送的对方已经不在线了
                $server->push($t_id,$msg);  //主动发送给$t_d
            }
            $num++;
        }
        echo '当前在线人数'.$num;

    }else{  //群发
        foreach ($server->connections as $conn){
            $server->push($conn,$msg);
        }
    }
});
$server->on('close', function ($server, $fd) {   //离开
    echo "{$fd} 下线了\n";
    unset($GLOBALS['fd'][$fd]);
});
$server->start();

二客户端



    
    Web sockets test
    
    








你可能感兴趣的:(swoole)