TCP连接如何在Android上运行?

时间:2015-09-25 06:06:59

标签: java android tcp smack

我正在使用smack在Android中构建聊天应用。我使用sticky_service来保持连接。我有一个困惑,如果我的应用程序进入睡眠状态TCP连接发生了什么。我在页面上看到了几个答案 - How to make the Android device hold a TCP connection to Internet without wake lock?

它会在短时间内醒来 - 对于smack,我可以将其视为processmessage listener(http://www.programcreek.com/java-api-examples/index.php?api=org.jivesoftware.smack.MessageListener)被调用。我在数据库中插入数据。是否有任何保证工作将完成,或者如果执行处于中间,将从那里开始。

1 个答案:

答案 0 :(得分:0)

您好亲爱的,您可以使用此代码段:

protected void connect() {
    Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
    features.encryptionEnabled = false;
    lastConnect = SystemClock.elapsedRealtime();
    lastPingSent = SystemClock.elapsedRealtime();
    this.attempt++;
    try {
        shouldAuthenticate = shouldBind = !account.isOptionSet(Account.OPTION_REGISTER);
        tagReader = new XmlReader(wakeLock);
        tagWriter = new TagWriter();
        packetCallbacks.clear();
        this.changeStatus(Account.State.CONNECTING);
        final Bundle result = DNSHelper.getSRVRecord(account.getServer());
        final ArrayList<Parcelable> values = result.getParcelableArrayList("values");
        if ("timeout".equals(result.getString("error"))) {
            throw new IOException("timeout in dns");
        } else if (values != null) {
            int i = 0;
            boolean socketError = true;
            while (socketError && values.size() > i) {
                final Bundle namePort = (Bundle) values.get(i);
                try {
                    String srvRecordServer;
                    try {
                        srvRecordServer = IDN.toASCII(namePort.getString("name"));
                    } catch (final IllegalArgumentException e) {
                        // TODO: Handle me?`
                        srvRecordServer = "";
                    }
                    final int srvRecordPort = namePort.getInt("port");
                    final String srvIpServer = namePort.getString("ip");
                    final InetSocketAddress addr;
                    if (srvIpServer != null) {
                        addr = new InetSocketAddress(srvIpServer, srvRecordPort);
                        Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
                                + ": using values from dns " + srvRecordServer
                                + "[" + srvIpServer + "]:" + srvRecordPort);
                    } else {
                        addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
                        Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
                                + ": using values from dns "
                                + srvRecordServer + ":" + srvRecordPort);
                    }
                    socket = new Socket();
                    socket.connect(addr, 20000);
                    socketError = false;
                } catch (final UnknownHostException e) {
                    Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
                    i++;
                } catch (final IOException e) {
                    Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
                    i++;
                }
            }
            if (socketError) {
                throw new UnknownHostException();
            }
        } else if (result.containsKey("error")
                && "nosrv".equals(result.getString("error", null))) {


             //todo:change here to server.


 socket = new Socket(server_ip, server port);

    } else {
        throw new IOException("timeout in dns");
    }
    final OutputStream out = socket.getOutputStream();
    tagWriter.setOutputStream(out);
    final InputStream in = socket.getInputStream();
    tagReader.setInputStream(in);
    tagWriter.beginDocument();
    sendStartStream();
    Tag nextTag;
    while ((nextTag = tagReader.readTag()) != null) {
        if (nextTag.isStart("stream")) {
            processStream(nextTag);
            break;
        } else {
            throw new IOException("unknown tag on connect");
        }
    }
    if (socket.isConnected()) {
        socket.close();
    }
} catch (final UnknownHostException | ConnectException e) {
    this.changeStatus(Account.State.SERVER_NOT_FOUND);
} catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
    Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
    this.changeStatus(Account.State.OFFLINE);
} finally {
    if (wakeLock.isHeld()) {


          try {
                wakeLock.release();
            } catch (final RuntimeException ignored) {
            }
        }
    }
}

享受您的代码:)