【问题标题】:How to check internet connection status with vibed?如何使用 vibed 检查互联网连接状态?
【发布时间】:2015-07-11 04:27:25
【问题描述】:

在应用启动之前,我需要检查互联网连接是否正常。做这个的最好方式是什么?我正在使用 vibed。

我写了下一段代码:

import std.stdio;
import std.string;
import std.conv;
import vibe.d;
import vibe.core.log;
import vibe.http.client;
import vibe.stream.operations;
import vibe.core.driver;

void main()
{

    HTTPClientResponse res = requestHTTP("http://www.example.org/");
    try
    {

        if (res.statusCode != 200)
        {
            logInfo("Check Internet connection, and try again!");
            logInfo("Server response is: " ~ to!string(res.statusCode));
        }
        else
        {
            logInfo("All ok");
        }
    }

    catch (Exception e)
    {
        writeln(e.msg);
    }
}

但如果我在没有互联网连接的情况下运行它,我会收到错误:

core.exception.AssertError@core.d(1177): No events registered, exiting event loop.

【问题讨论】:

  • 尝试建立与某个知名主机(例如 www.google.com)的连接,如果您未连接到 Internet,则会收到套接字错误...
  • 我上面的代码就是这样做的......

标签: d vibed


【解决方案1】:

你需要移动线

HTTPClientResponse res = requestHTTP("http://www.example.org/");

在try 块内捕获异常。

如果没有互联网连接,则通常没有可用的名称服务。这意味着在没有互联网连接的情况下很有可能抛出异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多