dongzhenjian5195 2017-07-13 22:53
浏览 123
已采纳

当脚本因阻塞io而超时时,如何生成自定义响应?

Goal

I am developing a JSON endpoint that basically reads data from a server-side COM port into a file (on the server end) when a user sends a GET request to it. The response from the server has to be a properly formed JSON response containing the name of the file where the contents were dumped to. If the COM port takes too long to respond, the file is closed and still considered valid with whatever contents it did read from the COM port. A valid response is still provided.

Problem

When the COM port is no longer being fed data, it blocks until the script times out. This results in an error and IIS provides a generic error page on a json endpoint. This is not valid json, but it also does not contain the name of the file where the com data was dumped to.

Details

  • I have to use the PHP Direct IO extension to interface with a serial com port.
  • This is blocking IO, and on windows, asynchronous IO is not supported (as far as I have seen.)
  • register_shutdown_function does not guarantee it is executed while a connection is still open to the client, so I cannot use this to print a valid response.
  • 写回答

1条回答 默认 最新

  • douyangcheng4965 2017-07-13 23:42
    关注

    For your JSON endpoint, you could create a wrapper script that calls your IO script. Set a timeout for your attempt to get a response from it, and then return JSON with either whatever it got from the script, or some custom message if the script timed out.

    $timeout = 5;  // some reasonable time less than the wrapper script timeout
    
    $data = ['filename' => 'something'];            // create the file name
    $q = http_build_query($data);                   // pass it to the IO script
    
    $context = stream_context_create(['http'=> ['timeout' => $timeout]]);
    $response =  file_get_contents("http://yourserver/io_script.php?$q", false, $context);
    
    echo json_encode($data + ['data' => $response ?: 'no data']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!