Workerman 下载
WorkerMan实际上就是一个PHP代码包,如果你的PHP环境已经装好,只需要把WorkerMan源代码或者demo下载下来即可运行。
composer require workerman/workerman
php代码
下载好 WorkerMan 后就可以直接使用了
<?php
require __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
// 使用websocket协议监听6161端口
$worker = new Worker('websocket://0.0.0.0:6162');
// 打开一个文件,给文件追加内容
function myFwrite($text) {
date_default_timezone_set('Asia/Shanghai');//设置时区
$myTime = date("Y/m/d h:i:s");
//追加(append)方式打开02.txt文件,文件不在会自动创建
$fp = fopen('./server.log','a');
//给文件写入内容
fwrite($fp, $text." " . $myTime ."\r\n");
//关闭文件
fclose($fp);
};
$worker->onConnect = function(TcpConnection $connection) {
// $cmd = ["cmd" => "send/deviceinfo"];
$connection->send('发送给web数据');
};
// 当浏览器(包括用户手机浏览器和电脑浏览器)发来消息时的处理逻辑
$worker->onMessage = function(TcpConnection $connection, $data) {
// 把web发送的数据记录一下你也可以不需要这个
myFwrite($data);
// web发送的数据
switch ($data) {
// 发送 daping 字符串的是电脑浏览器,将其连接保存到静态变量中
case '"test"':
$connection->send($devirce2);
break;
// ping 是心跳数据,用来维持连接,只返回 pong 字符串,无需做其它处理
case 'ping':
$connection->send('pong');
break;
case '"lang"':
$connection->send($lang);
break;
case '"updateDevice"':
$connection->send($getDeviceupdate);
break;
default:
if ($daping_connection) {
$daping_connection->send($data);
}
}
};
Worker::runAll();
使用
配置好php环境变量 使用命令 php youFileName.php 就可以直接允许了 这里的 youFileName 是你文件的名字