2014-11-04 49 views
1

我的android应用程序连接服务器与TCP套接字,以确保连接是好的,服务器每隔10秒发送一次“keep-alive”消息,我可以在WireShark中抓取数据包,但在我的应用程序中,我可以在任何地方都无法处理数据包,似乎无法使用套接字读取数据包。如何对android中的“keep-alive”包做出反应?

下面是我的套接字连接的代码段。看来,“保持活动”数据包就不能与InputStream的读取...

public class SocketBase { 
    private Socket mSocket; 
    private DataOutputStream out; 
    private DataInputStream in; 
    private SocketCallback callback; 
    private int timeOut = 1000 * 30; 


    public SocketBase(SocketCallback callback) { 
     this.callback = callback; 
    } 


    public void connect(String ip, int port) throws Exception { 
     mSocket = new Socket(); 
     SocketAddress address = new InetSocketAddress(ip, port); 
     mSocket.connect(address, timeOut); 
     if (mSocket.isConnected()) { 
      out = new DataOutputStream(mSocket.getOutputStream()); 
      in = new DataInputStream(mSocket.getInputStream()); 
      callback.connected(); 
     } 
    } 


    public void write(byte[] buffer) throws IOException { 
     if (out != null) { 
      out.write(buffer); 
      out.flush(); 
     } 
    } 


    public void disconnect() { 
     try { 
      if (mSocket != null) { 
       if (!mSocket.isInputShutdown()) { 
        mSocket.shutdownInput(); 
       } 
       if (!mSocket.isOutputShutdown()) { 
        mSocket.shutdownOutput(); 
       } 
       if (out != null) { 
        out.close(); 
       } 
       if (in != null) { 
        in.close(); 
       } 
       mSocket.close(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      callback.disconnect(); 
      out = null; 
      in = null; 
      mSocket = null; 
     } 
    } 


    public void read() throws IOException { 
     if (in != null) { 
      byte[] buffer = new byte[1024*1]; 
      byte[] tmpBuffer; 
      int len = 0; 
      Log.i("SOCKET", "something comming"); 
      while ((len = in.read(buffer)) > 0) { 
       tmpBuffer = new byte[len]; 
       System.arraycopy(buffer, 0, tmpBuffer, 0, len); 
       callback.receive(tmpBuffer); 
       tmpBuffer = null; 
      } 
     } 
    } 
} 

在Wireshark中的“保持活动”包是这样的:

Keep-alive packet

+0

目前尚不清楚你在说什么。你的意思是什么“保活包”?你真的意指一个普通的TCP保持活着吗?你100%确定吗? – 2014-11-04 02:14:51

回答

2

如果你的意思是一个普通的TCP保持活着,你没有什么可以检测或做的。你的TCP实现负责确认它。它里面没有应用数据,所以你没有什么可读的。

+0

我想要做的是检测“保持活跃”,并决定客户端是否与服务器失去连接,现在当我关闭服务器时,实际上连接丢失,但没有任何“通知”客户端,这样我可以做一些“最终”的工作。 – smallzhan 2014-11-04 02:27:01

+0

@smallzhan哦,那不可能工作。您需要尝试将数据发送到服务器或自己发送保活邮件。 – 2014-11-04 03:08:29

相关问题