Workerman chat system

Download address of documents and files

Chat plug-in library: Workerman
file: http://doc2.workerman.net/
Manual: http://www.workerman.net/gatewaydoc/
Download Demo: http://doc2.workerman.net/
CatewayWorker server installation of Linux: http://www.workerman.net/download/GatewayWorker.zip
CatewayWorker server installation Window: http://www.workerman.net/download/GatewayWorker-for-win.zip

General principles for the combination of GatewayWorker framework and MVC:

The existing mvc framework project and gateway worker are deployed independently without interference

All business logic is completed by the website page post/get into the mvc framework

The gateway worker does not accept the data sent by the client, that is, the gateway worker does not process any business logic, and the gateway worker is only used as a one-way push channel

The API of Gateway is only invoked in the mvc framework only when the mvc framework needs to push data to the browser actively. GatewayClient Complete push.

Client installation

composer Installing GatewayClinet Client

composer require workerman/gatewayclient
//Introduction during use vendor/autoload.php Similar to the following: use GatewayClient\Gateway; require_once 'Real path/vendor/autoload.php';

Or download the source file to any directory and manually import the gateway client / gateway PHP, similar to the following:

use GatewayClient\Gateway;
require_once 'Real path/GatewayClient/Gateway.php';

Server installation

CatewayWorker server installation, you can directly download the source file

composer require workerman/gateway-worker-for-win //install Windows Version gateway
composer require workerman/gateway-worker //install Linux Version gateway

The server-side project directory structure is separately deployed by gateway worker

├── Applications // Here are all developer applications
│   └── YourApp  // One of the project directories. The directory name can be customized
│       ├── Events.php // Developers only need to focus on this file
│       ├── start_gateway.php // gateway Process startup script, including port number and other settings
│       ├── start_businessworker.php // businessWorker Process startup script
│       └── start_register.php // Registration service startup script
│
├── start.php // Global startup script, which will be loaded in turn Applications/project/start_*.php Startup script
│
└── vendor    // GatewayWorker Framework and Workerman Framework source code directory, which developers do not need to care about

 

Server file operation

Create start Bat, usually put in the root directory, Window startup file, double-click

php worker\win\start_register.php worker\win\start_gateway.php worker\win\start_businessworker.php
pause

Create start PHP, usually placed in the root directory, the Linux startup file, and the command line PHP start php start

/**
 * run with command
 * php start.php start Official website file
 */

ini_set('display_errors', 'on');
use Workerman\Worker;

if(strpos(strtolower(PHP_OS), 'win') === 0)
{
    exit("start.php not support windows, please use start_for_win.bat\n");
}

// Check extension
if(!extension_loaded('pcntl'))
{
    exit("Please install pcntl extension. See http://doc3.workerman.net/appendices/install-extension.html\n");
}

if(!extension_loaded('posix'))
{
    exit("Please install posix extension. See http://doc3.workerman.net/appendices/install-extension.html\n");
}

// Flag is global startup
define('GLOBAL_START', 1);

require_once __DIR__ . '/worker/vendor/autoload.php';

// Load all Applications/*/start.php,In order to start all services, I put the root directory here/worker/win/ Next, the other files to start are start.bat File specified in file
foreach(glob(__DIR__.'/worker/win/start*.php') as $start_file)
{
    require_once $start_file;
}
// Run all services
Worker::runAll();

Two startup methods: start_gateway.php start_businessworker.php start_register.php is the process startup script, and the three scripts are unified by the start. PHP in the root directory php/ start. Bat starts.

Document description

start_register.php} starts a script for the registration service, which is used to coordinate the communication between the Gateway and the Worker within the Gateway Worker cluster. See the section on using the Register class.

Note: the client should not connect to the Register service port, but should connect to the Gateway port

use \Workerman\Worker;
use \GatewayWorker\Register;

// Automatically load classes and customize them according to requirements
require_once __DIR__ . '/../../vendor/autoload.php';

// register Must be text agreement
$register = new Register('text://127.0.0.1:1234');

// If it is not started in the root directory, run runAll method
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}

start_gateway.php} is the Gateway process startup script, which mainly defines the port number, protocol and other information of the client connection. For details, see the section on using the Gateway class.

use \Workerman\Worker;
use \Workerman\WebServer;
use \GatewayWorker\Gateway;
use \GatewayWorker\BusinessWorker;
use \Workerman\Autoloader;

// Auto load class
require_once __DIR__ . '/../vendor/autoload.php';
/**
 * Establish a websocket connection with GatewayWorker, and change the domain name and port to your actual domain name and port,
 * The port is the Gateway port, i.e. start_gateway.php specified port.
 * start_gateway.php You need to specify the websocket protocol in, like this
 * $gateway = new Gateway(websocket://0.0.0.0:7272);
 * js part:
 * ws = new WebSocket("ws://your_domain.com:7272");
 */
// gateway Process, used here Text Agreement, can be used telnet test

$context = array(
    // more ssl Refer to the manual for options http://php.net/manual/zh/context.ssl.php
    'ssl' => array(
        // Please use absolute path
        'local_cert'                 => __dir__.'/certificate/server.pem', // It can also be crt file
        'local_pk'                   => __dir__.'/certificate/server.key',
        'verify_peer'               => false,
        // 'allow_self_signed' => true, //This option needs to be turned on if it is a self signed certificate
    )
);
// websocket agreement(Any port, as long as it is not occupied by other programs)
$gateway = new Gateway("websocket://0.0.0.0:8899", $context);
// open SSL,websocket+SSL Namely wss
$gateway->transport = 'ssl';
// gateway name, status Easy to view
$gateway->name = 'YourAppGateway';
// gateway Number of processes
$gateway->count = 4;
// Local machine IP,Use Intranet in distributed deployment IP,GatewayWorker And GatewayClient The current server intranet is not used on the same server IP,If not in the same intranet, change to the public network IP
$gateway->lanIp = '127.0.0.1';
// Internal communication start port, if $gateway->count=4,The starting port is 4000
// Generally, 4000 4001 4002 4003 ports will be used as internal communication ports 
$gateway->startPort = 2900;
// Service registration address
$gateway->registerAddress = '127.0.0.1:1238';

// heartbeat interval 
//$gateway->pingInterval = 10;
// Heartbeat data
//$gateway->pingData = '{"type":"ping"}';

/* 
// When the client connects, set the onWebSocketConnect of the connection, that is, the callback during the websocket handshake
$gateway->onConnect = function($connection)
{
    $connection->onWebSocketConnect = function($connection , $http_header)
    {
        // You can judge whether the connection source is legal here. If not, close the connection
        // $_SERVER['HTTP_ORIGIN']Identifies the websocket link initiated by the page from which site
        if($_SERVER['HTTP_ORIGIN'] != 'http://kedou.workerman.net')
        {
            $connection->close();
        }
        // onWebSocketConnect Inside$_ GET $_SERVER is available
        // var_dump($_GET, $_SERVER);
    };
}; 
*/

// If it is not started in the root directory, run runAll method
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}

start_businessworker.php} starts the script for the BusinessWorker process, that is, calls events For the business processing process of PHP, see the section on the use of BusinessWorker class.

use \Workerman\Worker;
use \Workerman\WebServer;
use \GatewayWorker\Gateway;
use \GatewayWorker\BusinessWorker;
use \Workerman\Autoloader;

// Auto load class
require_once __DIR__ . '/../../vendor/autoload.php';

// bussinessWorker process
$worker = new BusinessWorker();
// worker name
$worker->name = 'YourAppBusinessWorker';
// bussinessWorker Number of processes
$worker->count = 4;
// Service registration address
$worker->registerAddress = '127.0.0.1:1234';

// If it is not started in the root directory, run runAll method
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}

Events.php # all the business code is here

 /* 
* It is used to detect problems such as business code deadlock or long-time blocking * If the business card is found dead, you can open the following declare (remove the / / comment) and execute PHP start php reload * Then observe the workman for a period of time Log to see if there is a process_timeout exception */
//declare(ticks=1); use \GatewayWorker\Lib\Gateway; /** * Main logic * It mainly deals with three methods: onconnect, onmessage and onclose * onConnect And onClose can be implemented and deleted if not required */ class Events { /** * Triggered when the client connects * If the service does not need this callback, you can delete onConnect * @param int $client_id Connection id * @desc $client_id Automatically generated for the system */ public static function onConnect($client_id) { // To current client_id send data /*Gateway::sendToClient($client_id, "Hello $client_id\r\n"); // Send to everyone Gateway::sendToAll("$client_id login\r\n");*/ } /** * Triggered when the client sends a message * @desc type:0 Open link and send other messages * @param int $client_id Connection id * @param mixed $message Specific information */ public static function onMessage($client_id, $message) { // Send to everyone Gateway::sendToAll("$client_id said $message\r\n"); } /** * Triggered when the user disconnects * @param int $client_id Connection id */ public static function onClose($client_id) { } }

 

Start and stop

Note: worker man start stop and other commands are completed on the command line.

start-up

Start in debug mode

php start.php start

Start as a daemon

php start.php start -d

stop it

php start.php stop

restart

php start.php restart

graceful restart

php start.php reload

View status

php start.php status

The difference between debug and daemon

1. Start in debug mode, echo and VaR in the code_ Dump, print and other printing functions will be directly output to the terminal.

2. Start in daemon mode, echo and VaR in the code_ Dump, print and other printing will be redirected to / dev/null file by default. You can set Worker::$stdoutFile = '/your/path/file'; To set the file path.

3. Start in debug mode. After the terminal is shut down, the worker man will shut down and exit.

4. Start in daemon mode. After the terminal is closed, the worker man continues to run normally in the background.

Keywords: PHP

Added by airo on Wed, 19 Jan 2022 09:02:23 +0200