Home  >  Article  >  PHP Framework  >  Using Nginx reverse proxy Websocket in ThinkPHP6

Using Nginx reverse proxy Websocket in ThinkPHP6

WBOY
WBOYOriginal
2023-06-20 21:31:401753browse

In recent years, Websocket has become a very important communication protocol in Internet applications. ThinkPHP6, as an excellent PHP development framework, also provides support for Websocket. However, when using Websocket, we usually involve issues such as cross-domain and load balancing. Therefore, in this article, we will introduce how to use Nginx reverse proxy Websocket in ThinkPHP6.

First of all, we need to clarify the basic principles and implementation methods of Websocket. Websocket uses the handshake process of the HTTP protocol to establish a connection. After the connection is established, the TCP protocol is used for actual data transmission. Therefore, for the use of Websocket, we need to consider both the HTTP and TCP parts.

In practical applications, we usually use Nginx reverse proxy for Websocket load balancing and cross-domain processing. Let's introduce how to use Nginx reverse proxy Websocket in ThinkPHP6.

1. Nginx configuration

We can implement reverse proxy for Websocket through the Nginx configuration file. First, we need to declare an upstream in the http block:

http {
    upstream websocket_servers {
        server 127.0.0.1:8000;
        server 127.0.0.1:8001;
    }
}

In the above configuration, we declared an upstream named websocket_servers, which contains two server addresses. In this way, when the client requests Websocket, Nginx will forward the request to one of the servers according to the load balancing algorithm.

Next, add the following configuration in the server block:

server {
    listen 80;
    server_name example.com;

    # 处理WebSocket请求
    location /ws {
        proxy_pass http://websocket_servers;
        proxy_set_header Host $http_host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 86400;
    }

    # 处理其他请求
    location / {
        proxy_pass http://backend_server;
        proxy_set_header Host $http_host;
    }
}

The above configuration will listen to port 80 and divide the request into two situations. When the client requests /ws, it will be forwarded to the websocket_servers declared above; other requests will be forwarded to backend_server.

For Websocket requests, we need to set some special request headers, such as Upgrade and Connection. Here we set these request headers through proxy_set_header. Note that the proxy_pass here must be the http protocol, not the https protocol.

2. ThinkPHP6 configuration

In ThinkPHP6, we need to start the Websocket service through Swoole Server. We can start a simple Websocket service through the following code:

<?php
use SwooleWebSocketServer;
use SwooleHttpRequest;
use SwooleWebSocketFrame;

$server = new Server("0.0.0.0", 8000, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);

$server->on("start", function (Server $server) {
    echo "Swoole WebSocket Server is started at http://0.0.0.0:8000
";
});

$server->on("open", function (Server $server, SwooleHttpRequest $request) {
    echo "connection open: {$request->fd}
";
    $server->push($request->fd, "hello, welcome
");
});

$server->on("message", function (Server $server, Frame $frame) {
    echo "received message: {$frame->data}
";
    $server->push($frame->fd, json_encode(["hello", "world"]));
});

$server->on("close", function (Server $server, $fd) {
    echo "connection close: {$fd}
";
});

$server->start();

In the above code, we created a WebSocket server and listened to port 8000. In the open event, we will receive a connection request from the client and send a welcome message to it. In the message event, we receive the message sent by the client and reply with a message. (The reply message here is just a simple example, and needs to be modified according to actual needs in actual applications.)

It should be noted here that when using Nginx reverse proxy Websocket, we must use Swoole's WebSocket server Bind to the port under the TCP protocol, not the port under the HTTP protocol. Therefore, we need to set the 3rd parameter to SWOOLE_SOCK_TCP.

We can also use Swoole's multi-process mode to improve performance. In the 4th parameter, we can set it to SWOOLE_PROCESS and specify a number to represent the number of processes.

In actual applications, we may need to use some database or cache functions in the Websocket service, which can be easily implemented through the dependency injection function of ThinkPHP6.

3. Front-end code

Finally, let’s take a look at how the front-end code uses Websocket.

var ws_url = "ws://example.com/ws";  // 注意这里的协议必须是ws

var websocket = new WebSocket(ws_url);

websocket.onopen = function () {
    console.log("WebSocket opened");
};

websocket.onmessage = function (evt) {
    console.log("WebSocket received message:", evt.data);
};

websocket.onclose = function () {
    console.log("WebSocket closed");
};

In the above code, we communicate with the server through the WebSocket object. When a connection is opened, the onopen event is triggered, when a message is received, the onmessage event is triggered, and when the connection is closed, the onclose event is triggered.

It should be noted that the protocol here must be ws, not http or https.

4. Summary

Through the above introduction, we can find that it is very easy to use Nginx reverse proxy Websocket in ThinkPHP6. You only need to perform some basic configuration in Nginx and start a WebSocket server in Swoole, and you can use WebSocket to communicate on the front end. If you encounter problems in actual applications, you can refer to the above code to fix them.

The above is the detailed content of Using Nginx reverse proxy Websocket in ThinkPHP6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn