【问题标题】:Getting an error trying to connect to mongodb database on android尝试连接到 android 上的 mongodb 数据库时出错
【发布时间】:2021-10-15 21:11:16
【问题描述】:

我得到的错误是

com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 27017) from /127.0.0.1 (port 43950) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)}, caused by {android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)}}]

我假设这里的问题是 AVD 使用与我的计算机相同的 IP,但如果我尝试在 AVD 的设置中更改它,它无法连接到 androidWifi。 (我尝试将其更改为 10.0.2.2,因为这是我在另一个 stackoverflow 帖子中找到的解决方案,但它不起作用。)

如果重要的话,我的代码如下所示:

    MongoClient client = MongoClients.create("mongodb://localhost:27017");
    MongoDatabase db = client.getDatabase("userData");
    MongoCollection<Document> users = db.getCollection("users");

    Document user = new Document("name", "user").append("password", "pass");

    users.insertOne(user);

【问题讨论】:

  • ECONNREFUSED 表示目标上的操作系统主动拒绝连接,因为该端口上没有任何东西在监听。
  • 是的。不过,这是对这个问题的可怕解释。这可能是正在发生的事情,但它与为什么会发生完全没有关系。正如我刚刚发现的那样,原因是因为将连接设置为本地主机,将其设置为 android 的本地主机,而不是运行 AVD 的计算机。

标签: java android mongodb


【解决方案1】:

为后代添加此答案 - 发生此错误的原因是因为在该行中:

 MongoClient client = MongoClients.create("mongodb://localhost:27017");

数据库地址设置为 ANDROID 的本地主机,而不是托管 AVD 的 PC。要解决此问题,请使用命令 ipconfig 查找您的 ipv4 地址 然后在 CMD 中运行 mongo shell 时输入以下命令:mongod --bind_ip "yourIPHere"

请注意,如果有人碰巧拥有您的内部 IP 地址,这会将您的数据库打开到外部连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-09
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多