如何对android中的“keep-alive”包做出反应?

时间:2014-11-04 02:05:07

标签: android sockets tcp

我的Android应用程序连接服务器与TCP套接字,以确保连接正常,服务器空闲时每10秒发送“保持活动”消息,我可以在WireShark中抓取数据包,但在我的应用程序中,我无法在任何地方处理数据包,似乎无法用套接字读取数据包。

以下是我的套接字连接的代码段。似乎无法使用输入流读取“保持活动”数据包...

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”数据包是这样的:

Keep-alive packet

1 个答案:

答案 0 :(得分:2)

如果您的意思是常规的TCP保持活动,那么您无需检测或执行任何操作。您的TCP实现负责确认它。其中没有应用程序数据,因此您无需阅读。