웹 애플리케이션의 개발로 인해 온라인 채팅, 주식 시장 추진 및 기타 시나리오에서 실시간 커뮤니케이션이 중요해졌습니다. WebSocket 프로토콜을 통해 브라우저 및 서버는 지속적인 양방향 연결을 설정하여 효율적인 실시간 데이터 교환을 가능하게합니다. 이 기사는 PHP 및 WebSocket 프로토콜을 사용하여 실시간 통신을 완료하고 코드 예제를 통해이를 시연하는 방법을 소개합니다.
WebSocket 프로토콜은 TCP 프로토콜을 기반으로하며 전체 이중 통신을 지원합니다. WebSocket을 사용하면 서버가 데이터를 적극적으로 푸시 할 수 있으며 클라이언트는 즉시 응답 할 수 있습니다. 주요 기능은 다음과 같습니다.
PHP는 WebSocket을 직접 지원하지는 않지만 내선 라이브러리를 통해 관련 기능을 구현할 수 있습니다. 일반적으로 사용되는 연장은 다음과 같습니다.
이 기사는 Ratchet Extension을 사용하여 WebSocket Communication의 구현 프로세스를 보여줍니다.
작곡가를 통해 래칫 설치 :
<span class="fun">작곡가에는 CBoden/래칫이 필요합니다</span>
다음 예제는 모든 연결된 클라이언트에게 메시지를 수신하고 방송하는 간단한 서버를 보여줍니다.
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
<p>require 'vendor/autoload.php';</p>
<p>class MyWebSocketServer implements MessageComponentInterface {<br>
protected $clients;</p>
<pre class="overflow-visible!"><div class="contain-inline-size rounded-2xl border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary"><div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none rounded-t-2xl">php</div><div class="sticky top-9"><div class="absolute end-0 bottom-0 flex h-9 items-center pe-2"><div class="bg-token-sidebar-surface-primary text-token-text-secondary dark:bg-token-main-surface-secondary flex items-center gap-4 rounded-sm px-2 font-sans text-xs"><button class="flex gap-1 items-center select-none py-1" aria-label="복사"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon-xs"><path fill-rule="evenodd" clip-rule="evenodd" d="M7 5C7 3.34315 8.34315 2 10 2H19C20.6569 2 22 3.34315 22 5V14C22 15.6569 20.6569 17 19 17H17V19C17 20.6569 15.6569 22 14 22H5C3.34315 22 2 20.6569 2 19V10C2 8.34315 3.34315 7 5 7H7V5ZM9 7H14C15.6569 7 17 8.34315 17 10V15H19C19.5523 15 20 14.5523 20 14V5C20 4.44772 19.5523 4 19 4H10C9.44772 4 9 4.44772 9 5V7ZM5 9C4.44772 9 4 9.44772 4 10V19C4 19.5523 4.44772 20 5 20H14C14.5523 20 15 19.5523 15 19V10C15 9.44772 14.5523 9 14 9H5Z" fill="currentColor"></path></svg>복사</button><button class="flex items-center gap-1 py-1 select-none"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon-xs"><path d="M2.5 5.5C4.3 5.2 5.2 4 5.5 2.5C5.8 4 6.7 5.2 8.5 5.5C6.7 5.8 5.8 7 5.5 8.5C5.2 7 4.3 5.8 2.5 5.5Z" fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M5.66282 16.5231L5.18413 19.3952C5.12203 19.7678 5.09098 19.9541 5.14876 20.0888C5.19933 20.2067 5.29328 20.3007 5.41118 20.3512C5.54589 20.409 5.73218 20.378 6.10476 20.3159L8.97693 19.8372C9.72813 19.712 10.1037 19.6494 10.4542 19.521C10.7652 19.407 11.0608 19.2549 11.3343 19.068C11.6425 18.8575 11.9118 18.5882 12.4503 18.0497L20 10.5C21.3807 9.11929 21.3807 6.88071 20 5.5C18.6193 4.11929 16.3807 4.11929 15 5.5L7.45026 13.0497C6.91175 13.5882 6.6425 13.8575 6.43197 14.1657C6.24513 14.4392 6.09299 14.7348 5.97903 15.0458C5.85062 15.3963 5.78802 15.7719 5.66282 16.5231Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M14.5 7L18.5 11" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>편집하다</button></div></div></div><div class="overflow-y-auto p-4" dir="ltr">public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
$client->send($msg);
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "Error: {$e->getMessage()}\n";
$conn->close();
}
}
$ server = new \ ratchet \ server \ ioserver (
new \ ratchet \ http \ httpserver (
new \ ratchet \ websocket \ wsserver (
새로운 MyWebsocketServer ()
))
),)
New \ React \ Socket \ Server ( '0.0.0.0:8000', New \ React \ EventLoop \ StreamSelectLoop ())
);
$ server-> run ();
다음 클라이언트 예제는 서버에 연결, 메시지 보내기 및 응답 수신을 구현합니다.
<?php
use Ratchet\Client\WebSocket;
use Ratchet\Client\Connector;
use React\EventLoop\Factory as EventLoopFactory;
<p>require 'vendor/autoload.php';</p>
<p>$loop = EventLoopFactory::create();<br>
$connector = new Connector($loop);</p>
<p>$connector('ws://localhost:8000')->then(function(WebSocket $conn) {<br>
$conn->on('message', function($msg) use ($conn) {<br>
echo "Received: {$msg}\n";<br>
$conn->close();<br>
});</p>
<pre class="overflow-visible!"><div class="contain-inline-size rounded-2xl border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary"><div class="flex items-center text-token-text-secondary px-4 py-2 text-xs font-sans justify-between h-9 bg-token-sidebar-surface-primary dark:bg-token-main-surface-secondary select-none rounded-t-2xl">perl</div><div class="sticky top-9"><div class="absolute end-0 bottom-0 flex h-9 items-center pe-2"><div class="bg-token-sidebar-surface-primary text-token-text-secondary dark:bg-token-main-surface-secondary flex items-center gap-4 rounded-sm px-2 font-sans text-xs"><button class="flex gap-1 items-center select-none py-1" aria-label="복사"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon-xs"><path fill-rule="evenodd" clip-rule="evenodd" d="M7 5C7 3.34315 8.34315 2 10 2H19C20.6569 2 22 3.34315 22 5V14C22 15.6569 20.6569 17 19 17H17V19C17 20.6569 15.6569 22 14 22H5C3.34315 22 2 20.6569 2 19V10C2 8.34315 3.34315 7 5 7H7V5ZM9 7H14C15.6569 7 17 8.34315 17 10V15H19C19.5523 15 20 14.5523 20 14V5C20 4.44772 19.5523 4 19 4H10C9.44772 4 9 4.44772 9 5V7ZM5 9C4.44772 9 4 9.44772 4 10V19C4 19.5523 4.44772 20 5 20H14C14.5523 20 15 19.5523 15 19V10C15 9.44772 14.5523 9 14 9H5Z" fill="currentColor"></path></svg>복사</button><button class="flex items-center gap-1 py-1 select-none"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon-xs"><path d="M2.5 5.5C4.3 5.2 5.2 4 5.5 2.5C5.8 4 6.7 5.2 8.5 5.5C6.7 5.8 5.8 7 5.5 8.5C5.2 7 4.3 5.8 2.5 5.5Z" fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M5.66282 16.5231L5.18413 19.3952C5.12203 19.7678 5.09098 19.9541 5.14876 20.0888C5.19933 20.2067 5.29328 20.3007 5.41118 20.3512C5.54589 20.409 5.73218 20.378 6.10476 20.3159L8.97693 19.8372C9.72813 19.712 10.1037 19.6494 10.4542 19.521C10.7652 19.407 11.0608 19.2549 11.3343 19.068C11.6425 18.8575 11.9118 18.5882 12.4503 18.0497L20 10.5C21.3807 9.11929 21.3807 6.88071 20 5.5C18.6193 4.11929 16.3807 4.11929 15 5.5L7.45026 13.0497C6.91175 13.5882 6.6425 13.8575 6.43197 14.1657C6.24513 14.4392 6.09299 14.7348 5.97903 15.0458C5.85062 15.3963 5.78802 15.7719 5.66282 16.5231Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M14.5 7L18.5 11" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>편집하다</button></div></div></div><div class="overflow-y-auto p-4" dir="ltr">$conn->send('Hello, WebSocket Server!');
}, function (\ Exception $ e) 사용 ($ loop) {
echo "연결할 수 없습니다 : {$ e-> getMessage ()} \ n";
$ loop-> stop ();
});
$ loop-> run ();
명령 줄에서 서버 및 클라이언트를 시작하십시오.
php server.php
php client.php
현재 클라이언트와 서버는 실시간 데이터의 양방향 통신을 실현할 수 있습니다.
이 기사는 PHP를 사용하여 실시간 통신을 위해 WebSocket 프로토콜을 결합하여 Ratchet 확장의 설치 및 코드 구현을 보여주는 기본 방법을 소개합니다. WebSocket 프로토콜을 통해 PHP 응용 프로그램은 효율적인 서버 푸시 및 클라이언트 응답을 달성하여 최신 웹 실시간 상호 작용의 요구를 충족시킬 수 있습니다.