群聊天 群内消息发送
<?php
/**
* @ Copyright 2017-2018 VARIANT TECHNOLOGY CO.,LTD All Rights Reserved.
* Created by PhpStorm.
* @author [wolf]
* @version [版本号,2019/4/23 9:46]
* @see [相关文件,类,函数]
* @since [产品/模块]
* @deprecated
*/
namespace app\user\controller;
use think\Controller;
use think\Db;
use think\worker\Server;
use Workerman\Lib\Timer;
class ChatController extends Server
{
protected $socket = 'websocket://127.0.0.1:3000';
protected $processes = 10;
/**
* 收到信息
*
* @param $connection
* @param $data
*/
public function onMessage($connection, $data)
{
$arr = json_decode($data, true);
global $worker;
if($arr['type'] == 1)
{//验证用户是否是群主
//建立聊天室
if(!isset($uid))
{
$uid = $arr['business_id'];//群id
}
$connection->uid = $uid;
$worker->uidConnections[$connection->uid] = $this->worker->connections;
foreach ( $this->worker->connections as $connection)
{
if($connection->uid == $uid)
{//向指定uid的用户发送消息
$connection->send($arr['content']);
}
}
}
else if($arr['type'] == 2)
{
if(!isset($uid))
{
$uid = $arr['a_business_id'];//群id
}
$connection->uid = $uid;
$worker->uidConnections[$connection->uid] = $this->worker->connections;
foreach ( $this->worker->connections as $connection)
{
if($connection->uid == $uid)
{//向指定uid的用户发送消息
$connection->send($arr['content']);
}
}
}
}
/**
*
* @param $connection当连接建立时触发的回调函数
*/
public function onConnect($connection)
{
$connection->uid = '';
}
/**
* 当连接断开时触发的回调函数
*
* @param $connection
*/
public function onClose($connection)
{
/*global $worker;
if(isset($uid))
{
// 连接断开时删除映射
unset($worker->uidConnections[$uid]);
}*/
}
/**
* 当客户端的连接上发生错误时触发
*
* @param $connection
* @param $code
* @param $msg
*/
public function on
{
echo "error $code $msg\n";
}
/**
* 每个进程启动
*
* @param $worker
*/
public function onWorkerStart($worker)
{
}
//向所有验证的用户推送数据
public function broadcast($message)
{
global $worker;
foreach ($worker->uidConnections as $connection)
{
$connection->send($message);
}
}
}