on
[PHP] Ratchet Websocket 설치 및 사용방법
[PHP] Ratchet Websocket 설치 및 사용방법
//composer.json에서 설정한 namespace
namespace ServerClass;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class RatchetSocket implements MessageComponentInterface {
protected $clients ;
public function __construct() {
// clients 변수에 접속 클라이언트들을 담을 객체 생성
$this - > clients = new \SplObjectStorage;
}
// 클라이언트 접속
public function onOpen(ConnectionInterface $conn ) {
// clients 객체에 클라이언트 추가
$this - > clients - > attach( $conn );
echo "New connection! ({$conn->resourceId}) / Clients Count : {$this->clients->count()}
" ;
}
//메세지 전송, $from 인자값은 메세지를 보낸 클라이언트의 정보, $msg인자값은 보낸 메세지
public function onMessage(ConnectionInterface $from , $msg ) {
//접속한 clients 수만큼 반복
foreach ( $this - > clients as $client ) {
//접속한 클라이언트 본인 이외일때
if ( $from ! = = $client ) {
//메세지 전송
$client - > send( $msg );
}
}
}
//클라이언트 접속 종료
public function onClose(ConnectionInterface $conn ) {
// clients 객체에 클라이언트 접속정보 제거
$this - > clients - > detach( $conn );
echo "Connection {$conn->resourceId} has disconnected
" ;
}
public function onError(ConnectionInterface $conn , \Exception $e ) {
echo "An error has occurred: {$e->getMessage()}
" ;
$conn - > close();
}
}
from http://ganbarujoy.tistory.com/150 by ccl(A) rewrite - 2021-09-15 13:00:52