2016-07-16 2 views
0

주기적으로 "안녕하세요!"메시지를 보내려고합니다. Chat.php :정기적으로 라쳇에있는 고객에게 메시지 보내기

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

class Chat implements MessageComponentInterface { 
    public $clients; 

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

    public function onOpen(ConnectionInterface $conn) { 
     // Store the new connection to send messages to later 
     $this->clients->attach($conn); 

     echo "New connection! ({$conn->resourceId})\n"; 
    } 

    //this worked but I don't want this behaviour 
    public function onMessage(ConnectionInterface $from, $msg) { 
     /*$numRecv = count($this->clients) - 1; 
     echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n" 
      , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's'); 

     foreach ($this->clients as $client) { 
      if ($from !== $client) { 
       // The sender is not the receiver, send to each client connected 
       $client->send($msg); 
      } 
     }*/ 
    } 

    public function onClose(ConnectionInterface $conn) { 
     // The connection is closed, remove it, as we can no longer send it messages 
     $this->clients->detach($conn); 

     echo "Connection {$conn->resourceId} has disconnected\n"; 
    } 

    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 MyApp\Chat; 

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

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

    $server->run(); 
래칫 튜토리얼에서 채팅 서버에 연결된 모든 클라이언트에 메시지가

나는 여기에 모든 코드를 게시 할 예정입니다

, 나는 서버의 루프에 타이머를 추가 어떻게 이해 문서의 많은 테스트하려면

<?php 
    use Ratchet\Server\IoServer; 
    use MyApp\Chat; 

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

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


     // My code here 
     $server->loop->addPeriodicTimer(5, function() { 
      echo "custom loop timer working !";   
     }); 


     $server->run(); 

그리고 서버를 시작한 후 5 초마다 해당 문자열을 출력하는 데 문제가 없습니다.

지금 내가 튜토리얼

$server->loop->addPeriodicTimer(5, function() {   
    foreach ($server->app->clients as $client) {     
      $client->send("hello client");   
    } 
}); 

에서 채팅라는 MessageComponentInterface에 저장된 클라이언트에 메시지를 보내려고, 그래서 같이 그 일을 시도하지만 그 $ 서버 -납니다> 응용 프로그램 인 NULL입니다 아마도 함수() 블록 안에 있기 때문입니다. 객체 지향 PHP는 전문가가 아니기 때문에이 작은 프로젝트가 도움이 될 것입니다. MessageComponentInterfaceapp 타이머 내부의 서버 속성에 액세스 한 다음 거기에 저장된 클라이언트로 데이터를 보내려면 어떻게해야합니까?

+0

것은 (기능'후'사용 ($ 서버)'추가)' –

+0

'클로저도 상속 할 수 있습니다 변수 부모 범위에서. 그러한 변수는 사용 언어 구조에 전달되어야합니다. 'https://secure.php.net/manual/en/functions.anonymous.php –

+0

'$ server'는 클로저에서 정의되지 않았기 때문에 NULL입니다. 함수 범위. 그것에 대해 더 자세히 읽어보십시오. https://secure.php.net/manual/en/language.variables.scope.php –

답변

2

$server은 함수 범위에 정의되어 있지 않으며 부모 범위의 변수는 기본적으로 자식 범위로 상속되지 않습니다. 클로저는 use 언어 구조를 사용하여 상위 범위에서 변수를 상속 할 수 있습니다. 익명 함수에 대한

$server->loop->addPeriodicTimer(5, function() use ($server) {   
    foreach ($server->app->clients as $client) {     
      $client->send("hello client");   
    } 
}); 

상세 정보 (폐쇄) : https://secure.php.net/manual/en/functions.anonymous.php
변수 범위에 대한 더 많은 정보 : https://secure.php.net/manual/en/language.variables.scope.php