| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <?php
- namespace App\Services\Socket;
- use App\Services\RedisService;
- use Ratchet\MessageComponentInterface;
- use Ratchet\ConnectionInterface;
- class ChatService implements MessageComponentInterface
- {
- protected $clients;
- public function __construct()
- {
- $this->clients = new \SplObjectStorage;
- }
- public function onOpen(ConnectionInterface $conn)
- {
- $this->clients->attach($conn);
- echo "Socket:创建【{$conn->resourceId}】连接成功! \n";
- }
- public function onMessage(ConnectionInterface $from, $msg)
- {
- echo "Socket:".$msg.'++'.$from->resourceId."\n";
- $fromId = $from->resourceId;
- $data = $msg? json_decode($msg, true) : [];
- $type = isset($data['type'])? $data['type'] : '';
- $ct = isset($data['ct'])? $data['ct'] : '';
- $uuid = isset($data['uuid'])? $data['uuid'] : uniqid();
- $fromData = isset($data['data'])? $data['data'] : '';
- $date = date('Y-m-d H:i:s');
- switch($type){
- case 'bind':
- if($ct){
- RedisService::set("caches:server:{$fromId}", ['uuid'=>$uuid,'fromId'=>$fromId,'date'=>$date], 7 * 3600);
- }
- RedisService::set("caches:{$uuid}:{$type}", ['uuid'=>$uuid,'qrcode'=>$fromData,'formId'=>$fromId,'date'=>$date], 7 * 24 * 3600);
- //RedisService::set("caches:{$uuid}:qrcode", ['uuid'=>$uuid,'qrcode'=>$formData,'formId'=>$formId,'date'=>$date], 7 * 24 * 3600);
- $from->send(json_encode(['type'=>'bind','result'=>'ok']));
- break;
- case 'login-bind':
- var_dump($this->clients);
- RedisService::set("caches:binds:login", ['uuid'=>$uuid,'data'=>$fromData,'formId'=>$fromId,'date'=>$date], 7 * 24 * 3600);
- RedisService::set("caches:{$uuid}:{$type}", ['uuid'=>$uuid,'data'=>$fromData,'formId'=>$fromId,'date'=>$date], 7 * 24 * 3600);
- foreach ($this->clients as $conn){
- if(RedisService::get("caches:server:".$conn->resourceId)){
- $conn->send(json_encode(['type'=>'login-load','uuid'=>$uuid,'mid'=>$conn->resourceId,'data'=> $fromData,'t'=>time()], 256));
- }
- }
- break;
- default:
- RedisService::set("caches:{$uuid}:{$type}", ['uuid'=>$uuid,'data'=>$fromData,'formId'=>$fromId,'date'=>$date], 7 * 24 * 3600);
- //RedisService::set("caches:{$uuid}:qrcode", ['uuid'=>$uuid,'qrcode'=>$formData,'formId'=>$formId,'date'=>$date], 7 * 24 * 3600);
- break;
- }
- $from->send(json_encode(['type'=> $type,'result'=>'ok','t'=>time()], 256));
- }
- public function onClose(ConnectionInterface $conn)
- {
- $this->clients->detach($conn);
- RedisService::keyDel("caches:server:".$conn->resourceId);
- echo "Socket:Connection {$conn->resourceId} has disconnected\n";
- }
- public function onError(ConnectionInterface $conn, \Exception $e)
- {
- echo "Socket:An error has occurred: {$e->getMessage()}\n";
- $conn->close();
- }
- }
|