[php] Start Using HTML5 WebSockets Today With a PHP Server 지금 PHP 서버에서 HTML5 WebSocket 사용 시작
HTML5의 흥미로운 기능 중 하나는 AJAX 요청을 사용하지 않고 서버와 통신할 수 있는 WebSocket입니다. 이 자습서에서는 PHP에서 WebSocket 서버를 실행한 다음 WebSocket 프로토콜을 통해 메시지를 보내고 받는 클라이언트를 빌드하는 프로세스를 검토합니다.
One of the exciting features of HTML5 is WebSockets, which let us talk to the server without using AJAX requests. In this tutorial, we'll review the process of running a WebSocket server in PHP, and then building a client to send and receive messages to it over the WebSocket protocol.
What Are WebSockets?
A WebSocket is a persistent bi-directional communication channel between a client (e.g. a browser) and a back-end service. In contrast with HTTP request/response connections, WebSockets can transport any number of protocols and provide server-to-client message delivery without polling.
What Do WebSockets Replace?
WebSockets are designed to address the limitations of traditional HTTP-based communication. Before the introduction of WebSockets, HTTP requests and responses were stateless, meaning that each request/response pair was independent of previous and subsequent requests/responses. Due to that, it was really difficult to implement real-time communication, where the server needs to push data to the client as soon as it becomes available.
WebSockets also provide advantages over older technologies such as AJAX long polling and server-sent events (SSE). WebSockets can replace long polling easily. This is an interesting concept. The client sends a request to the server, and now, rather than the server responding with data it may not have, it essentially keeps the connection open until the fresh, up-to-date data is ready to be sent. The client next receives this and sends another request. This has its benefits: decreased latency being one of them, as a connection which has already been opened does not require a new connection to be established. However, long polling isn't really a piece of fancy technology: it's also possible for a request to time out, and thus a new connection will be needed anyway.
Many AJAX applications make use of the above—this often leads to poor resource utilization.
Wouldn't it be great if the server could send data to clients who are willing to listen without some sort of pre-established connection? Welcome to the world of push technology!
Overall, WebSockets provide a more efficient and effective solution for real-time communication, and they have become really popular for building real-time web applications.
Install the Ratchet WebSockets Library
Ratchet is a PHP library which enables building real-time, bi-directional, and event-driven applications with WebSockets. Today, we'll use this library to implement the WebSockets server.
To install the Ratchet WebSockets library, you need to use Composer, which is a dependency manager for PHP. Here are the steps to install Ratchet using Composer.
I assume that Composer is already installed on your system. With that in place, you can use the following Composer command to install the Ratchet library.
Upon successful installation, it should create the following composer.json file.
So we've now installed the Ratchet WebSockets library successfully.
Create the WebSockets Server
In this section, we'll see how to create a WebSockets server in PHP.
Create the server.php file with the following contents.
First of all, we've defined a
WebSocketsServer class, which implements the
MessageComponentInterface interface, which provides the necessary callback functions for handling WebSocket events like connections, messages, and disconnections.
Our code then creates a new
IoServer instance, which is the main entry point for running a WebSocket server. Finally, it starts the server by calling the
run() method of the
WebSockets is an event-driven protocol. Let's quickly go through each event defined in the
onOpen(ConnectionInterface $conn): triggered when a new client connects to the WebSocket server. The
$conn parameter holds the connection object of the new client. In this method, we've added connections to the
$clients storage object.
onMessage(ConnectionInterface $from, $msg): one of the most important events. It's triggered when any client sends a message from the client side to the WebSocket server. The
$from parameter holds the connection object of the client who sent the message, and
$msg is the message content. Also, we loop through all the clients in the
$clients storage object and send the message to all clients except the sender client.
onClose(ConnectionInterface $conn): triggered when any client disconnects from the WebSocket server. The
$conn parameter holds the connection object of the client. In this method, we've removed the connection from the
$clients storage object.
onError(ConnectionInterface $conn, \Exception $e): triggered when an error occurs on the WebSocket server. The
$conn parameter holds the connection object of the client where the error occurred, and
$e is the error object.
Starting the Server
To start the WebSockets server, go ahead and run the following command on the command line.
Now, our web server is running successfully on port 8089. You can confirm this by running the following command in another tab, and it should provide the output as shown in the following snippet.
Implement the WebSockets Client
Create the client.php file with the following contents.
Let's understand how the above code works.
Firstly, there's the HTML structure of the client-side WebSocket user interface.
If the browser supports WebSockets, the
connect() function is called, which creates a WebSocket object and connects it to the server running on
connect() function also defines event listeners for the WebSocket object.
Let's quickly see the event listeners that we've defined for the WebSocket object.
onopen: called when the connection is created. It sends a message to the chat area to indicate that the connection is open.
onmessage: called when a message is received from the server. It appends the received message to the chat area.
onclose: called when the connection is closed. It sends a message to the chat area to indicate that the connection is closed.
Apart from that, we've also built a few helper functions.
send() function is called when a user enters a message and hits the Enter button. It sends the message to the server using the WebSocket object and appends the sent message to the chat area. The
message() function is called to append messages to the chat area. Finally, the Disconnect button calls the
close() function of the WebSocket object to close the connection.
How to Test the App
As we discussed earlier, go ahead and run the following command on the command prompt to start the WebSockets server.
Next, open http://localhost/client.php in a few different tabs. When the page loads, a WebSocket connection will be opened. So for example, if you've opened this URL in three different tabs, there will be three WebSocket client connections.
Now, when you enter the message and press Enter in one tab, the same message will be broadcast to other tabs as well by the WebSockets server. You can click on the Disconnect button to close the WebSocket connection.
So that's how you can use WebSockets in PHP with the help of the Ratchet library.