//服务端定时发送数据
use \Workerman\Worker;
use \Workerman\Connection\AsyncTcpConnection;
use \Workerman\Lib\Timer;
require_once './Workerman/Autoloader.php';
define('PING_TIMEOUT', 5);
$worker = new Worker('websocket://0.0.0.0:8484');
// 进程启动时设置一个定时器,定时向所有客户端连接发送数据
$worker->onWorkerStart = function($worker)
{
// 定时,每10秒一次
Timer::add(1, function()use($worker)
{
// 遍历当前进程所有的客户端连接,发送当前服务器的时间
foreach($worker->connections as $connection)
{
var_dump($connection->id);
$connection->send(time()."\n");
}
});
};
// 运行worker
Worker::runAll();
//=========客户端8484端口接收数据
use \Workerman\Worker;
use \Workerman\Connection\AsyncTcpConnection;
use \Workerman\Lib\Timer;
require_once './Workerman/Autoloader.php';
define('PING_TIMEOUT', 5);
$task = new Worker();
// 进程启动时异步建立一个到www.baidu.com连接对象,并发送数据获取数据
$task->onWorkerStart = function($connection)
{
connect($connection);
};
function connect($connection){
$connection->lastTime = time();
$connection_to_baidu = new AsyncTcpConnection('ws://127.0.0.1:8484');
// 当连接建立成功时,发送http请求数据
$connection_to_baidu->onConnect = function($connection_to_baidu)
{
echo "connect success\n";
};
$connection_to_baidu->onMessage = function($connection_to_baidu, $http_buffer)
{
echo $http_buffer;
};
$connection_to_baidu->onClose = function($connection_to_baidu)use($connection)
{
echo "connection closed\n";
Timer::add(1, function()use($connection) {
$time_now = time();
if($time_now - $connection->lastTime > PING_TIMEOUT) {
connect($connection);
}
});
};
$connection_to_baidu->onError = function($connection_to_baidu, $code, $msg)use($connection)
{
echo "error $code $msg\n";
//connect($connection);
};
$connection_to_baidu->connect();
}
// 运行worker
Worker::runAll();
//如果服务端没启动,五秒重连 ,等一会服务端启动了 会有很多tcp链接
//如果没有定时器,直接connect($connection); 会不停的重连,直到内存溢出
//这个怎么处理 写定时器不行么(想定时重连这个websocket)
只要onclose 时重连就行了,onerror时不用设置重连,因为异步连接失败时也会触发onclose。另外你的定时器应该在每次onclose时只运行一次,而不是不断的定时连接,不断的连接如果服务端可连接会产生无数的连接,最后内存耗尽
嗯嗯 搞定了