2015-06-20 11 views
7

Kullanıcının websocket sunucusuna bağlantı kurma konusunda bir kategoriye abone olabileceği bir sistem oluşturmaya çalışıyorum ve o kategori için güncellemeleri almaya başlayacağım. Şimdiye kadar, Ratchet ile çalıştım ve tüm bağlı istemcilere mesaj gönderebiliyorum ama sorun mesaj göndermek istemediğim müşterilere mesaj göndermek istediğim tüm müşterilere mesaj göndermek istemiyorum. Mesajların gönderildiği belirli kategori.Belirli kullanıcılara mesajlar nasıl gönderilir? Ratchet PHP Websocket

PHP Kod

Chat.php

<?php 
namespace MyApp; 
use Ratchet\MessageComponentInterface; 
use Ratchet\ConnectionInterface; 

class Chat implements MessageComponentInterface 
{ 
    protected $clients; 

    public function __construct() 
    { 
     $this->clients = new \SplObjectStorage; 
    } 

    public function onOpen(ConnectionInterface $conn) 
    { 
     $this->clients->attach($conn); 
    } 

    public function onMessage(ConnectionInterface $conn, $msg) 
    { 
     foreach ($this->clients as $client) 
     { 
      if($conn !== $client) 
       $client->send($msg); 
     } 
    } 

    public function onClose(ConnectionInterface $conn) 
    { 
     $this->clients->detach($conn); 
    } 

    public function onError(ConnectionInterface $conn, \Exception $e) 
    { 
     echo "An error has occurred: {$e->getMessage()}\n"; 
     $conn->close(); 
    } 
} 
?> 

server.php

<?php 
use Ratchet\Server\IoServer; 
use Ratchet\Http\HttpServer; 
use Ratchet\WebSocket\WsServer; 
use MyApp\Chat; 

require dirname(__DIR__) . '/Ratchet/vendor/autoload.php'; 

$server = IoServer::factory(
    new HttpServer(
    new WsServer(
     new Chat() 
    ) 
), 
    8080 
); 

$server->run(); 
?> 

İstemci tarafının js kodu

<script type="text/javascript"> 
var conn = new WebSocket('ws://localhost:8080'); 

conn.onopen = function(e) { 
    console.log("Connection established!"); 
}; 

conn.onmessage = function(e) { 
    console.log(e.data); 
}; 
</script> 

cevap

21

Temel olarak veri göndermek için bir sözdizimi istiyorum WebSocket, ben reccom Bunu yapmak için bir JSON nesnesini kullanarak bitirin. WebSocket sınıfınızda, subscriptions adlı yerel bir değişkene ve users adlı yerel bir değişkene ihtiyacınız vardır. Bununla gidecek

<?php 
namespace MyApp; 
use Ratchet\MessageComponentInterface; 
use Ratchet\ConnectionInterface; 

class Chat implements MessageComponentInterface 
{ 
    protected $clients; 
    private $subscriptions; 
    private $users; 

    public function __construct() 
    { 
     $this->clients = new \SplObjectStorage; 
     $this->subscriptions = []; 
     $this->users = []; 
    } 

    public function onOpen(ConnectionInterface $conn) 
    { 
     $this->clients->attach($conn); 
     $this->users[$conn->resourceId] = $conn; 
    } 

    public function onMessage(ConnectionInterface $conn, $msg) 
    { 
     $data = json_decode($msg); 
     switch ($data->command) { 
      case "subscribe": 
       $this->subscriptions[$conn->resourceId] = $data->channel; 
       break; 
      case "message": 
       if (isset($this->subscriptions[$conn->resourceId])) { 
        $target = $this->subscriptions[$conn->resourceId]; 
        foreach ($this->subscriptions as $id=>$channel) { 
         if ($channel == $target && $id != $conn->resourceId) { 
          $this->users[$id]->send($data->message); 
         } 
        } 
       } 
     } 
    } 

    public function onClose(ConnectionInterface $conn) 
    { 
     $this->clients->detach($conn); 
     unset($this->users[$conn->resourceId]); 
     unset($this->subscriptions[$conn->resourceId]); 
    } 

    public function onError(ConnectionInterface $conn, \Exception $e) 
    { 
     echo "An error has occurred: {$e->getMessage()}\n"; 
     $conn->close(); 
    } 
} 
?> 

javascript biraz bu

<script type="text/javascript"> 
var conn = new WebSocket('ws://localhost:8080'); 

conn.onopen = function(e) { 
    console.log("Connection established!"); 
}; 

conn.onmessage = function(e) { 
    console.log(e.data); 
}; 

function subscribe(channel) { 
    conn.send(JSON.stringify({command: "subscribe", channel: channel})); 
} 

function sendMessage(msg) { 
    conn.send(JSON.stringify({command: "message", message: msg})); 
} 
</script> 

Not benziyor: Bu kod Ben Ratchet ile benim deneyimlerinden anında yazdım test edilmedi. İyi şanslar :)

+0

Aslında Ratchet Pusher'i kullanmam gerekiyor. Ve ben herşeyin iyi çalıştığını ama şimdi sorun şu ki, istemcinin mesaj kesmeyi bıraktığı bir bağlantı kesilmesi olmadan birkaç dakika boşta kaldıktan sonra bağlantısı kesiliyor. Her 10 dakikada bir müşteriye mesajlaşmaya devam edersem, bağlantı kesilmez, ancak 20 dakikadan fazla bir boşluk varsa, istemci mesaj alamaz. –

+0

@RohitKhatri Web bağlantısına bağlanmak için ne kullanıyorsunuz? Nginx'i mi yoksa bir şey mi yapıyorsun? – MarshallOfSound

+0

Bu örnekten Pusher ile Ratchet kullanıyorum [link] (http://socketo.me/docs/push) –

İlgili konular