【问题标题】:SocketException when there is no internet connection没有互联网连接时的 SocketException
【发布时间】:2016-12-14 19:50:32
【问题描述】:

我正在编写一个应用程序,该应用程序在服务中打开套接字并将一些数据发送到服务器并侦听传入数据。当在 android 设备上失去与互联网的连接时,当然会出现问题。

这是我得到的代码 sn-p

java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed 出)

try{
        mSocket = new Socket("xxx.xxx.xxx.xxx", xxxxx);
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
        String s;
        while((s = in.readLine())!= null){ //here error of course
            ...
        }
        mSocket.close();
    }catch(Exception e){
        e.printStackTrace();
    }

当 Internet 连接丢失并且BufferedReader 尝试 readLine()。如何避免这种情况,为什么会这样?

更新

在我尝试执行下一个场景之前,错误并没有打扰我: 1)在打开wifi的情况下运行socket 2)打开移动数据 3)关闭wifi

当wifi关闭时出错,但我通过移动数据连接到互联网,所以我想继续在套接字上收听而不会出错。这可能吗?如何实现?

【问题讨论】:

  • 不要断开互联网连接...?这不是很明显,当您没有连接时,会抛出某种Exception 吗?你应该像现在一样捕捉它并为用户打印有关丢失连接的信息
  • 请尝试,while (in.ready()) { s = in .readLine(); ... }
  • 我更新了帖子。
  • 这里没有要解决的“问题”。当连接丢失时,您正确地收到异常。 Thisnisnexsctly应该发生什么。不清楚你在问什么。
  • 你看到更新了吗?如果我连接到互联网,但与套接字启动的连接类型不同,则会出现异常。

标签: java android sockets exception tcp


【解决方案1】:

你应该做的是在你的 catch 块中重新连接一个新的套接字。原来的连接现在已经没有了,我不知道“无缝”交换它的方法。

try {
  mSocket = new Socket("xxx.xxx.xxx.xxx", xxxxx);
  ...
} catch(Exception e){
    try {
      mSocket = new Socket("xxx.xxx.xxx.xxx", xxxxx);
      ...
    } catch (Exception e2) {
      // OK you really lost connectivity at this point, tell the user.
    }
}

【讨论】:

  • 连接并没有真正丢失,只是连接类型从 wifi 更改为移动数据。
  • 正如我所说,我认为您不能像那样交换连接类型。我相信 TCP 实际上会终止连接,因此需要一个新的Socket。
  • @DomenJakofčič 你错了。连接丢失。套接字坏了,必须关闭。
  • 感谢两个答案,我并不完全理解这是如何工作的。所以现在我在 catch 块中添加下一个代码 if(networkAvailable){ stopService(); startService()} 并且它工作正常。我知道存在一些极端情况,但我会尝试处理它们。
猜你喜欢
  • 2014-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 2013-02-23
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
相关资源
最近更新 更多