preface

As you know, PHP is very convenient for developing web applications based on HTTP protocol. HTTP is a one-way communication protocol. It can only receive requests from clients and then respond to requests, but cannot actively push information to clients. Therefore, some applications with high real-time requirements, such as real-time chat, live streaming applications and online web games, are not suitable for HTTP protocol. Even if the client adopts the mode of active polling to realize the two-way communication indirectly, it will greatly increase the burden of the server, increase the complexity of the code, and is not conducive to maintenance.

So is PHP incapable of developing applications for two-way communication?

The answer is no. PHP built-in socket communication support, and Linux programs based on socket two-way communication. The PHP Swoole framework encapsulates a Websocket server, which makes it easy to build a service that communicates with html5 websocket clients.

Swoole introduction

Swoole is a production-oriented PHP asynchronous network communication engine that enables PHP developers to write high-performance asynchronous concurrent TCP, UDP, Unix Socket, HTTP, and WebSocket services. Swoole can be widely used in the Internet, mobile communications, enterprise software, cloud computing, online gaming, Internet of Things (IOT), Internet of vehicles, smart home and other fields. Using PHP + Swoole as a network communication framework can greatly improve the efficiency of enterprise IT r&d teams.

Swoole supports setting up a variety of servers, including HTTP Server, Websocket Server, TCP Server, Redis Server and so on. Here we use the WebSocket Server.

Second, WebSocket introduction

WebSocket is a protocol for full duplex communication over a single TCP connection. The WebSocket communication protocol was standardized by THE IETF in 2011 as RFC 6455, and is supplemented by RFC7936. The WebSocket API is also a W3C standard. WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.

Simply put, the WebSocket protocol implements bidirectional communication between the browser and the server. Html5 natively supports the Websocket protocol.

Swoole Websocket server Demo

1. Install swoole

Swoole is loaded as a PHP extension. First you need to install the Swoole extension for your PHP.

pecl install swoole
Copy the code

After successful installation, load the extension in the php.ini file with extension=swoole.so

2. Start the server

Create a new PHP file named server.php with the following contents:

$server = new Swoole\WebSocket\Server("0.0.0.0", 9501);
$server->on('open'.function (Swoole\WebSocket\Server $server.$request) {
        echo "server: handshake success with fd{$request->fd}\n";
    });
$server->on('message'.function (Swoole\WebSocket\Server $server.$frame) {
        echo "receive from {$frame->fd}:{$frame->data}\n";
        $server->push($frame->fd, "this is server");
    });
$server->on('close'.function ($ser.$fd) {
        echo "client {$fd} closed\n";
    });
$server->on('request'.function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
    global $server; // Call the external server //$server->connections Run through all FDS of websocket connections and push foreach ($server->connections as $fd) {// You need to check whether the websocket connection is correct, otherwise the push may failif ($server->isEstablished($fd)) {
            $server->push($fd.$request->get['message']); }}});$server->start();
Copy the code

This service listens on port 9501 of the machine and starts the service by running the command PHP server.php.

HTML5 WebSocket client Demo

1. Client code

Create a new testServer.html file and say the following:

<! Doctype HTML > < HTML > <head> <title> Test WebSocket</title> </head> <body> <script> var ws = new WebSocket("Ws :// [server IP] :9501");
        ws.onopen = function(event){
           console.log("connected!");
           ws.send("hello server,this is client!");
        };
        ws.onmessage= function(event){
           console.log(Server message: ""+event.data);
        }

        ws.onclose = function(event){
            console.log("closed!");
        };
    </script>
</body>

</html>
Copy the code

Replace [server IP] with swoole server IP and save the file.

Test demo

(1) Access the client demo page in Step 4. Connect to the server and view the browser console log. The following output is displayed:

connected!

(2) Check the Linux console, you can see the display:

server: handshake success with fd1

(3) Then the client sends a message to the server, and the server console displays:

receive from fd1:hello server,this is client!

(4) After receiving the message, the server replies a message to the client, and the console of the client displays:

Server message: This is the server

The above is a simple demonstration of developing two-way communication applications based on Swoole + Websocket. Real-time communication applications such as online chat and web games can also be developed in this way. PHP development efficiency, can be faster, more efficient development of such applications, saving development costs.

If you have any questions, you can pay attention to the public account “full stack community” to ask questions.


  • Pay attention to wechat public number “full stack community”, you can get more webmaster, developers necessary front-end, back-end, server technology dry goods.

  • Xu Cat Cloud 19 YUAN VPS:The VPS

  • Xumao Cloud free filing space:Hong Kong Cloud Host