douwen9343 2017-03-28 16:53
浏览 550

发送HTTP请求并等待30秒

i was wondering how can i send a HTTP request to a website and keep the connection live for 30 seconds and then kill it. Is it possible with PHP or Javascript?

For example: 1. Script sends a request to stackoverflow 2. The connection will be kept alive for 30 seconds 3. After expiring the connection will be closed.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • duanjia4817 2017-03-28 17:01
    关注

    Open the connection manually using fsockopen() so you can control the timing of sending the request and closing the connection.

    $conn = fsockopen("stackoverflow.com", 80);
    $request = "GET / HTTP/1.1
    " +
        "Host: stackoverflow.com
    " + 
        "Connection: keep-alive
    
    ";
    fputs($conn, $request);
    $response = fgets($conn);
    sleep(30);
    close($conn);
    

    Connection: keep-alive tells the server to keep the connection open until the client closes it (this is actually the default in HTTP/1.1, but no harm in sending it explicitly).

    However, most webservers have an inactivity timeout that will close connections that are idle. According to Wikipedia this defaults to 15 seconds in Apache httpd 1.3 and 2.0, and 5 seconds in httpd 2.2. So it's likely that the above code won't be effective. You would have to keep sending new requests every couple of seconds to keep the server from closing the connection.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?