我打印出$fd发现只有1和7,而只有7是有效的websocket连接。我发现只要打开一个直播页面,服务器就会关闭五次连接,如下图。请问老师为什么会这样子呢?
下面是我的代码
ws.php
<?php
/**
* ws 优化 基础类库
* User: singwa
* Date: 18/3/2
* Time: 上午12:34
*/
class Ws {
CONST HOST = "0.0.0.0";
CONST PORT = 8811;
public $ws = null;
public function __construct() {
$this->ws = new swoole_websocket_server(self::HOST,self::PORT);
$this->ws->set(
[
'worker_num' => 4,
'task_worker_num' => 4,
'enable_static_handler' => true,
'document_root' => "/usr/local/project/thinkphp/public/static",
]
);
$this->ws->on("message", [$this, 'onMessage']);
$this->ws->on("open", [$this, 'onOpen']);
$this->ws->on("workerstart", [$this, 'onWorkStart']);
$this->ws->on("request", [$this, 'onRequest']);
$this->ws->on("task", [$this, 'onTask']);
$this->ws->on("finish", [$this, 'onFinish']);
$this->ws->on("close", [$this, 'onClose']);
$this->ws->start();
}
/**
* 监听ws连接事件
* @param $ws
* @param $request
*/
public function onOpen($ws, $request) {
echo $request->fd;
}
/**
* 监听ws消息事件
* @param $ws
* @param $frame
*/
public function onMessage($ws, $frame) {
echo "ser-push-message:{$frame->data}\n";
$ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s"));
}
public function onWorkStart($server, $worker_id){
define('APP_PATH', __DIR__ . '/../application/');
require __DIR__ . '/../thinkphp/start.php';
}
public function onRequest($request, $response){
$_SERVER=[];
if(isset($request->server)){
foreach ($request->server as $k =>$v){
$_SERVER[strtoupper($k)]=$v;
}
}
if(isset($request->header)){
foreach ($request->header as $k =>$v){
$_SERVER[strtoupper($k)]=$v;
}
}
$_GET=[];
if(isset($request->get)){
foreach ($request->get as $k =>$v){
$_GET[$k]=$v;
}
}
$_POST=[];
if(isset($request->post)){
foreach ($request->post as $k =>$v){
$_POST[$k]=$v;
}
}
$_FILES=[];
if(isset($request->files)){
foreach ($request->files as $k =>$v){
$_FILES[$k]=$v;
}
}
$_POST['http_server']=$this->ws;
ob_start();
try{
think\Container::get('app', [APP_PATH ])
->run()
->send();
}catch (\Exception $e)
{
}
$res=ob_get_contents();
ob_end_clean();
$response->end($res);
}
/**
* @param $serv
* @param $taskId
* @param $workerId
* @param $data
*/
public function onTask($serv, $taskId, $workerId, $data) {
}
/**
* @param $serv
* @param $taskId
* @param $data
*/
public function onFinish($serv, $taskId, $data) {
}
/**
* close
* @param $ws
* @param $fd
*/
public function onClose($ws, $fd) {
echo "clientid:{$fd} closed\n";
}
}
new Ws();
live.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/7/15 0015
* Time: 10:48
*/
namespace app\admin\controller;
use app\common\lib\ali\Util;
class Live{
public function push(){
try{
foreach($_POST['http_server']->connections as $fd)
{
$res=$_POST['http_server']->connection_info($fd);
print_r($res);
echo PHP_EOL;
echo $fd;
echo PHP_EOL;
}
echo "当前服务器共有 ".count($_POST['http_server']->connections). " 个连接\n";
$_POST['http_server']->push(2,'hello');
}catch (\Exception $e){
echo $e;
}
}
}