【已解决】Failed to connect to 172.16.0.26 port 8787: Address already in use

云端

新整个webman,放到Linux上,写个简单的方法:

public function index(Request $request)
{
    return response('hello webman');
}

windows本地,写个for循环:

for ($i = 0; $i < 10000; $i++) {
    echo '循环:' . $i . '=>' . request_get($url) . PHP_EOL;
}

request_get方法:

function request_get(string $url, int $timeout = 10)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

    $rs = curl_exec($ch);
    if (curl_errno($ch)) {
        $err_msg = curl_error($ch);
        curl_close($ch);
        return json_encode(['code' => 50, 'msg' => $err_msg]);
    } else {
        curl_close($ch);
        return $rs;
    }
}

结果后期提示:

Failed to connect to 172.16.0.26 port 8787: Address already in use

相关图片:

这是什么原因呢?还请解惑。

2073 1 1
1个回答

xiuwang

curl是短连接,每次请求会占用本地一个端口,请求完毕后这个端口不会立刻释放。本地端口有限,当本地端口被快速用完就会报这个 Address already in use 错误了。
curl用长连接,也就是不主动curl_close,这样就不会不断的消耗本地端口,应该就不会报错了,request_get改成

function request_get(string $url, int $timeout = 10)
{
    static $ch;
    $ch = $ch ?: curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

    $rs = curl_exec($ch);
    if (curl_errno($ch)) {
        $err_msg = curl_error($ch);
        //curl_close($ch);
        return json_encode(['code' => 50, 'msg' => $err_msg]);
    } else {
        //curl_close($ch);
        return $rs;
    }
}
  • 云端 2022-07-21

    非常感谢,按照你的建议,的确不会出现这个问题了。谢谢。

年代过于久远,无法发表回答
×
🔝