use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class ChatServer implements MessageComponentInterface { protected $clients = []; protected $rooms = []; public function onOpen(ConnectionInterface $c) { $this->clients[$c->resourceId] = ['conn'=>$c,'room'=>null,'name'=>'User'.$c->resourceId]; $this->sendRooms(); } public function onMessage(ConnectionInterface $c, $msg) { $d = json_decode($msg,true); if ($d['type']=="create") { $id = time(); $this->rooms[$id]=['name'=>$d['name'],'users'=>[]]; $this->sendRooms(); } if ($d['type']=="join") { $this->clients[$c->resourceId]['room']=$d['room']; $this->rooms[$d['room']]['users'][]=$c; $this->sendUsers($d['room']); } if ($d['type']=="msg") { $r=$this->clients[$c->resourceId]['room']; foreach ($this->rooms[$r]['users'] as $u) $u->send(json_encode(['type'=>'msg','user'=>$this->clients[$c->resourceId]['name'],'text'=>$d['text']])); } if ($d['type']=="typing") { $r=$this->clients[$c->resourceId]['room']; foreach ($this->rooms[$r]['users'] as $u) if ($u!==$c) $u->send(json_encode(['type'=>'typing','user'=>$this->clients[$c->resourceId]['name']])); } } public function onClose(ConnectionInterface $c) { unset($this->clients[$c->resourceId]); } public function onError(ConnectionInterface $c, \Exception $e) {} private function sendRooms() { $data=[]; foreach ($this->rooms as $id=>$r) $data[]=['id'=>$id,'name'=>$r['name']]; foreach ($this->clients as $c) $c['conn']->send(json_encode(['type'=>'rooms','rooms'=>$data])); } private function sendUsers($room) { $names=[]; foreach ($this->rooms[$room]['users'] as $u) $names[]="User".$u->resourceId; foreach ($this->rooms[$room]['users'] as $u) $u->send(json_encode(['type'=>'users','users'=>$names])); } }