Home PHP Framework ThinkPHP Using Nginx reverse proxy Websocket in ThinkPHP6

Using Nginx reverse proxy Websocket in ThinkPHP6

Jun 20, 2023 pm 09:31 PM
thinkphp nginx websocket

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;
    }
}
Copy after login

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;
    }
}
Copy after login

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();
Copy after login

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");
};
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
How to configure nginx in Windows How to configure nginx in Windows Apr 14, 2025 pm 12:57 PM

How to configure Nginx in Windows? Install Nginx and create a virtual host configuration. Modify the main configuration file and include the virtual host configuration. Start or reload Nginx. Test the configuration and view the website. Selectively enable SSL and configure SSL certificates. Selectively set the firewall to allow port 80 and 443 traffic.

How to start containers by docker How to start containers by docker Apr 15, 2025 pm 12:27 PM

Docker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

How to check whether nginx is started How to check whether nginx is started Apr 14, 2025 pm 01:03 PM

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

How to create containers for docker How to create containers for docker Apr 15, 2025 pm 12:18 PM

Create a container in Docker: 1. Pull the image: docker pull [mirror name] 2. Create a container: docker run [Options] [mirror name] [Command] 3. Start the container: docker start [Container name]

How to configure cloud server domain name in nginx How to configure cloud server domain name in nginx Apr 14, 2025 pm 12:18 PM

How to configure an Nginx domain name on a cloud server: Create an A record pointing to the public IP address of the cloud server. Add virtual host blocks in the Nginx configuration file, specifying the listening port, domain name, and website root directory. Restart Nginx to apply the changes. Access the domain name test configuration. Other notes: Install the SSL certificate to enable HTTPS, ensure that the firewall allows port 80 traffic, and wait for DNS resolution to take effect.

How to check nginx version How to check nginx version Apr 14, 2025 am 11:57 AM

The methods that can query the Nginx version are: use the nginx -v command; view the version directive in the nginx.conf file; open the Nginx error page and view the page title.

What to do if nginx server is hung What to do if nginx server is hung Apr 14, 2025 am 11:42 AM

When the Nginx server goes down, you can perform the following troubleshooting steps: Check that the nginx process is running. View the error log for error messages. Check the syntax of nginx configuration. Make sure nginx has the permissions you need to access the file. Check file descriptor to open limits. Confirm that nginx is listening on the correct port. Add firewall rules to allow nginx traffic. Check reverse proxy settings, including backend server availability. For further assistance, please contact technical support.

See all articles