Home  >  Article  >  PHP Framework  >  Workerman development: How to implement a WebSocket server

Workerman development: How to implement a WebSocket server

WBOY
WBOYOriginal
2023-11-07 15:29:011306browse

Workerman development: How to implement a WebSocket server

How to use Workerman to implement WebSocket server

With the increasing popularity of WebRTC technology, game real-time communication, online chat and other applications, WebSocket technology has become more and more important. . Workerman is a high-performance asynchronous TCP, UDP, and Unix Socket network framework running in a PHP environment. It inherently supports high concurrency and is very suitable for developing WebSocket servers.

This article will introduce in detail how to use Workerman to implement a WebSocket server, including how to handle WebSocket connections, how to send and receive WebSocket messages, and how to integrate the framework with other libraries. A complete sample code is also provided at the end of the article.

  1. Installing Workerman

Before you start using Workerman, you need to install it. You can install it through Composer, or you can download the source code directly from GitHub and install it manually. Here we take Composer installation as an example:

composer require workerman/workerman
  1. Writing WebSocket server code

Before using Workerman to implement the WebSocket server, you need to first understand the working principle of the WebSocket protocol. WebSocket is a full-duplex, long-connection protocol. The client and server establish a connection through a handshake, and then can send messages to each other. WebSocket messages can be any data such as text, binary or even files, and the server can process it differently depending on the message type.

Implementing a WebSocket server using Workerman is very simple and only requires a few lines of code to complete. Here is an example:

require_once __DIR__ . '/vendor/autoload.php';
use WorkermanWorker;

// 创建一个Worker监听8090端口,使用websocket协议通讯
$wsWorker = new Worker("websocket://0.0.0.0:8090");

// 启动4个进程对外提供服务
$wsWorker->count = 4;

// 处理WebSocket连接的回调函数
$wsWorker->onConnect = function($connection) {
    echo "New connection
";
};

// 处理WebSocket消息的回调函数
$wsWorker->onMessage = function($connection, $data) {
    // 处理消息...
};

// 启动Worker
Worker::runAll();

First, we create a Worker instance and specify it to listen on port 8090 and communicate using the websocket protocol. Then set up 4 processes to start to handle a large number of concurrent connections. Worker supports multiple transmission protocols such as TCP, UDP, and Unix Socket, so we need to specify the WebSocket protocol.

In this example, we only define two callback functions:

  1. When a new WebSocket connection is established, the onConnect callback function will be called, and we can record it here Operations such as logs and online user statistics.
  2. When a WebSocket message is received, the onMessage callback function will be called. We need to process the message here, such as performing simple calculations, sending replies, etc.
  3. The last step is to start the Worker, which will start listening to the specified port and handle WebSocket connections and messages.
  4. WebSocket message processing

Through the onMessage callback function, we can receive the WebSocket message sent by the client. The data format can be text or binary. The way to process WebSocket messages depends on the application scenario. For example, online chat applications may need to implement functions such as broadcasting and point-to-point chat, while game applications need to implement microsecond-level real-time communication.

The following is a simple example that can print out the received message and reply to the client:

$wsWorker->onMessage = function($connection, $data) {
    echo "Received message: {$data}
";
    $connection->send("Received: {$data}");
};

The status of the WebSocket connection

After the WebSocket connection is established, The connection between client and server remains open. Through the onClose callback function, we can handle the event of disconnection:

$wsWorker->onClose = function($connection) {
    echo "Connection closed
";
};
  1. Integration Framework

Workerman can be easily integrated with other frameworks. Here we take the Laravel framework as an example to introduce how to use Workerman to implement a WebSocket server in Laravel.

First, we need to install Workerman in the Laravel project:

composer require workerman/workerman

Next, we can create a custom Artisan command to start the WebSocket server:

php artisan make:command WebSocketServer

Then in the app Write code in the /Console/Commands/WebSocketServer.php file:

<?php

namespace AppConsoleCommands;

use IlluminateConsoleCommand;
use WorkermanWorker;

class WebSocketServer extends Command {
    // 命令名称
    protected $name = 'websocket:server';

    // 命令描述
    protected $description = 'Start WebSocket server';

    // 执行命令
    public function handle() {
        // 创建Worker实例,监听8080端口
        $wsWorker = new Worker("websocket://0.0.0.0:8080");

        // 进程数量
        $wsWorker->count = 4;

        // 处理连接事件
        $wsWorker->onConnect = function($connection) {
            echo "New connection
";
        };

        // 处理消息事件
        $wsWorker->onMessage = function($connection, $data) {
            // 处理消息
        };

        // 运行Worker
        Worker::runAll();
    }
}

Finally, we can start the WebSocket server through the following command:

php artisan websocket:server

As you can see, it is very simple to implement the WebSocket server using Workerman , and can be easily integrated into other frameworks.

  1. Complete code example

The following is a complete WebSocket server example, which can receive messages sent by the client and perform simple processing, and reply with the processing results To the client:

count = 4;

// 处理WebSocket连接的回调函数
$wsWorker->onConnect = function($connection) {
    echo "New connection
";
};

// 处理WebSocket消息的回调函数
$wsWorker->onMessage = function($connection, $data) {
    echo "Received message: {$data}
";
    $result = "Received: {$data}";
    $connection->send($result);
};

// 处理连接断开事件的回调函数
$wsWorker->onClose = function($connection) {
    echo "Connection closed
";
};

// 启动Worker
Worker::runAll();

The above is all about using Workerman to implement a WebSocket server. Through the introduction of this article, I believe that readers have mastered the relevant technical knowledge and can also use these techniques in actual projects. Developed.

The above is the detailed content of Workerman development: How to implement a WebSocket server. 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