Android: 如何设置OutputStream的超时时间?

Android: How to set timeout for OutputStream?

我用Socket与客户交流。我在为 OutputStream 设置超时时遇到问题。 Socket 本身已经设置了超时。当我没有为 OutputStream 设置超时时,当互联网连接在 OutputStream out = socket.getOutputStream() 处关闭时,IOException 将在 15 分钟后 抛出。它会影响用户体验本身。

Socket.java

 // Create an SSLContext that uses our TrustManager
 final SSLContext context = SSLContext.getInstance("TLS");
 context.init(null, tmf.getTrustManagers(), null);

 SSLSocket socket = null;

 try{
     SSLSocketFactory sslsocketfactory = context.getSocketFactory();
     socket = (SSLSocket) sslsocketfactory.createSocket();
     socket.connect(new InetSocketAddress(<dstAddress>, <dstPort>), <timeout>);

     // Here is the point when the internet connection is loss
     OutputStream out = socket.getOutputStream();
     out.write(BytesUtil.hexStringToBytes(<requestParams>));
     out.flush();
  } catch(SocketTimeoutException se) {
     se.printStackTrace();
  } catch (IOException e) {
     // Will thrown after 15 minutes
     e.printStackTrace();
  } catch (Exception e) {
     e.printStackTrace();
  } finally {
     // close socket
     if (socket != null) {
        try {
           socket.close();
        } catch (IOException e) {
           e.printStackTrace();
        }
  }

参见 SocketServerSocket。 类 都有一个 setSoTimeout 方法来指定等待连接或等待接收数据时的最大等待时间。当该时间过去时,套接字抛出一个 SocketTimeoutException ,您可以使用错误消息或任何您想要的方式进行处理。 在执行您想要超时的操作之前,您必须调用 setSoTimeout()。 之前

while ((numberReceived = socketInputStream.read(buffer)) != -1) {
//You'll need to call
socket.setSoTimeout(2000);

然后将一个 catch(SocketTimeoutException) 部分添加到您已有的 try/catch 块中。