java.net.socketexception networkunreachable异常未在android socket.connect()中捕获非阻塞套接字

时间:2014-04-21 10:24:39

标签: java android sockets tcp

我在android中有一个非阻塞的tcp客户端。当我尝试连接到不在我的子网中的服务器时,我得到连接超时异常,这很好,因为它会将SYN数据包发送到目标5次(tcp_syn_retries),它将返回连接超时错误。

现在当我关闭移动设备中的WiFi时,现在我的移动设备中只有环回接口,并且没有显示busybox route命令的任何内容。在socket.connect()中没有捕获网络无法访问的异​​常,它返回false 。

此外,当我注册OP_CONNECT时,会引发connect事件,并且sock.isConnectionPending()和socketChannel.finishConnect()也会返回true,表示已成功建立连接,但没有到服务器的路由。

当我在Ubuntu 12.04中的java编译器中尝试相同的代码时,在非阻塞套接字的socket.connect()中捕获异常网络不可达。

一切都适用于在android和java编译器中阻塞客户端套接字。在android和java编译器中都捕获了网络不可达异常。

  this.server_ip = "192.168.1.2";
  this.port = 7000;
  try
  {
    // Create a new selector  
    this.selector = SelectorProvider.provider().openSelector();
    InetSocketAddress address = new InetSocketAddress(this.server_ip, this.port);
    this.clientChannel = SocketChannel.open();

    // Configure it as non blocking 
    this.clientChannel.configureBlocking(false);
    Boolean client_status;
    try
    {
      client_status = this.clientChannel.connect(address);
    }
   catch (Exception e) 
   {
     System.out.println(e);
     System.out.println("exception caught in connect");
     return;
   } 
    System.out.println("Client_Connect status "+client_status);
    this.clientChannel.register(this.selector, SelectionKey.OP_CONNECT);
  } 
  catch (Exception e) 
  {
    System.out.println(e);
    System.out.println("exception caught");
    return;
  } 

  while (true)
  {
    try
    { 
      //block for event 
      channels = this.selector.select();
      System.out.println("out of in select");
      // Iterate over the set of keys for which events are available
      Iterator<SelectionKey> selectedKeys = this.selector.selectedKeys().iterator();
      while (selectedKeys.hasNext()) 
      {
        SelectionKey key = (SelectionKey) selectedKeys.next();
        selectedKeys.remove();
        if (!key.isValid()) 
        {
          continue;
        }

        if (key.isReadable()) 
        {
          this.read(key);
        } 
        else if (key.isWritable()) 
        {
          this.write(key);
        }
        else if(key.isConnectable())
        {
          System.out.println("connect ready");

          SocketChannel sock = (SocketChannel )key.channel();
          if(sock.isConnectionPending())
          {
            try
            {
              while (!sock.finishConnect())
              {
                System.out.println("Connection in progress..");
              }
              System.out.println("Connected successfully");
              sock.register(this.selector, SelectionKey.OP_READ);

            } 
            catch(Exception e)
            {
              System.out.println("exception disconnected "+e);
              key.cancel();
              this.selector.wakeup();
            }
          }
        }
      }
    } 
    catch (Exception e) 
    {
      e.printStackTrace();
    }
  }

我错过了什么吗?有人可以帮我这个吗?

0 个答案:

没有答案