用于学习Workerman的虚拟机配置信息如下(至于环境的安装,请参考官方手册自行解决):
Distributor ID:Ubuntu
Description:Ubuntu 14.04 LTS
Release:14.04
Codename:trusty
Workerman: 3.1.9
PHP version: 5.5.9
我们先用Workerman写第一个实例,实例目录如下:
/var/happy
├── Apps // 我们的实例代码放个目录
├── Workerman // Workerman框架源代码
首先,我们在Apps目录下新建一个 test.php
use Workerman\Worker;
require_once '../Workerman/Autoloader.php';
$global_uid = 0;
$text_worker = null;
// 有客户端连接上来
function handler_connection($connection) {
global $global_uid;
$connection->uid = ++$global_uid;
}
// 客户端有数据发过来
function handler_message($connection, $data) {
global $text_worker;
foreach($text_worker->connections as $conn) {
$conn->send("User[{$connection->uid}] said: $data .\r\n");
}
}
// 有客户端关闭
function handler_close($connection) {
global $text_worker;
foreach($text_worker->connections as $conn) {
$conn->send("User[{$connection->uid}] Logout.\r\n");
}
}
$text_worker = new Worker("Text://0.0.0.0:2345");
$text_worker->count = 1;
$text_worker->name = 'textWorker';
$text_worker->onConnect = 'handler_connection';
$text_worker->onMessage = 'handler_message';
$text_worker->onClose = 'handler_close';
Worker::runAll();
代码写好后,我们在服务器上运行:
telnet上去进行测试
当然也可以是多客户端上去测试下,这个大家自行去测试。