<?php use \Workerman\Worker; use \Workerman\WebServer; use \GatewayWorker\Gateway; use \GatewayWorker\BusinessWorker; use \Workerman\Autoloader; use \Workerman\Connection\AsyncTcpConnection; use \Workerman\Lib\Timer; require_once './vendor/autoload.php'; $worker = new Worker (); $worker->onWorkerStart = 'connect'; function connect() { // 2000个链接 // if ($count ++ >= 400) { // return; // } for($count = 0; $count < 400; $count ++) { $func = function ($count) { $session_id = 'd34pkfuf88vom9ugptop7e5' . $count; // 建立异步链接 // $con = new AsyncTcpConnection ( 'ws://xxxx:8282' ); $con = new AsyncTcpConnection ( 'ws://xxxxx:8282' ); $con->onMessage = function ($con, $msg) use ($session_id, $count) { // 服务器消息推送 echo "recv $session_id $msg\n"; $msg = json_decode ( $msg, true ); if ($msg && isset ( $msg ['action'] )) { switch ($msg ['action']) { case 'broadcast' : $time = ( int ) date ( 'dHis', time () ); $con->send ( "{\"model\":\"__workerman\",\"action\":\"set_value\",\"value_key\":\"client_time\",\"value_value\":{$time}}" ); break; } } }; $con->onClose = function ($con) use ($session_id, $count) { echo "con $session_id close\n"; }; $con->onConnect = function ($con) use ($session_id, $count) { // $con->send ( "{\"model\":\"__workerman\",\"action\":\"set_value\",\"value_key\":\"score\",\"value_value\":{$val}}" ); // 模拟登录动作 $con->send ( "{\"model\":\"remote\",\"action\":\"msg\",\"remote_url\":\"http://xxxxxx/workerman_remote/do/\",\"params\":{\"model\":\"user\",\"action\":\"login\",\"rm_session_id\":\"{$session_id}\"}}" ); // 当前链接每10秒发个心跳包 $time = ( int ) date ( 'dHis', time () ); $con->send ( "{\"model\":\"__workerman\",\"action\":\"set_value\",\"value_key\":\"client_time\",\"value_value\":{$time}}" ); Timer::add ( 10, function () use ($con, $session_id, $count, $time) { // 每10秒推送一个消息 // $con->send ( "{\"model\":\"user\",\"action\":\"sys_time\",\"session_id\":\"{$session_id}\",\"client_time\":\"{$time}\"}" ); // 模拟数钱,一秒推送10个消息 for($i = 0; $i < 10; $i ++) { $val = ( int ) date ( 'dHis', time () ); $con->send ( "{\"model\":\"__workerman\",\"action\":\"set_value\",\"value_key\":\"score\",\"value_value\":{$val}}" ); } echo $count . " send complete\n"; } ); }; $con->connect (); echo $count . " connections complete\n"; }; $func ( $count ); } } Worker::runAll ();
在400条的情况下,内存用不了多少,稳定性也有保证,不过实际情况,还是得具体场景才能判断.