workerman使用教程(以WebSocket为例)

创建workerman.websocket.php文件,代码如下:

<?php
// +-----------------------------------------------------------------------------------------+ //
// | 使用WebSocket协议对外提供服务                                                           | //
// | 启动方式:/program/php/bin/php /inetpub/wwwroot/workerman/workerman.websocket.php start | //
// +-----------------------------------------------------------------------------------------+ //

use Workerman\Worker;
use Workerman\Connection\TcpConnection;

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

$worker = new Worker('websocket://0.0.0.0:2000');

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

// 接收到客户端发送过来的消息的回调函数
$worker->onMessage = static function (TcpConnection $connection, $data) {
    $connection->send("{$data},人生无处不青山。"); // 向客户端发送消息
};

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



启动服务器

[root@localhost ~]# /program/php/bin/php /inetpub/wwwroot/workerman/workerman.websocket.php start
 
Workerman[/inetpub/wwwroot/workerman/workerman.websocket.php] start in DEBUG mode
------------------------------------------- WORKERMAN --------------------------------------------
Workerman version:4.1.4          PHP version:8.1.7           Event-Loop:\Workerman\Events\Select
-------------------------------------------- WORKERS ---------------------------------------------
proto   user            worker          listen                      processes    status           
tcp     root            none            websocket://0.0.0.0:2000    4             [OK]            
--------------------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success. # 按Ctrl+C可停止服务器
^CWorkerman[workerman.websocket.php] stopping ...
Workerman[workerman.websocket.php] has been stopped
[root@localhost ~]#



客户端连接服务器,并向服务器进行通信

<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>workerman使用教程(以WebSocket为例)</title>
</head>
<body>
<script type="text/javascript">
var ws = new WebSocket('ws://192.168.*.*:2000');

// 打开WebSocket后的回调函数
ws.onopen = function () {
    ws.send('埋骨何须桑梓地'); // 向服务器发送消息
};

// 接收到服务器发过来消息后的回调函数
ws.onmessage = function (e) {
    console.log(e.data); // 埋骨何须桑梓地,人生无处不青山。
};
</script>
</body>
</html>

Copyright © 2024 码农人生. All Rights Reserved