【问题标题】:TCPsending crashes the App if server is down如果服务器关闭,TCPsending 会使应用程序崩溃
【发布时间】:2013-01-06 22:28:31
【问题描述】:

我为我们的全球 Leadbord 编写了一个服务器,它现在可以正常工作。 如果它处于活动状态,我可以向它发送数据。但如果它出现故障,我的应用程序不会停止。我没有得到解决方案我希望你能帮助我。这是发送:

public void saveToDatabase(LeadboardElement element2) {
    final LeadboardElement element = element2;
    send = false;
    // Need to be a thread! else android blocks it because it could take to
    // long to send!
    this.thread = new Thread() {
        public void run() {
            try {
                Socket soc = new Socket(Config.TCP_SERVERNAME_IP,
                        Config.TCP_PORT);
                DataOutputStream out = new DataOutputStream(
                        soc.getOutputStream());
                DataInputStream in = new DataInputStream(
                        new BufferedInputStream(soc.getInputStream()));

                // to call the save statement!
                out.writeInt(0);
                // give the stuff
                out.writeUTF(element.getName());
                out.writeInt(element.getLevel());
                out.writeInt(element.getKillPoints());

                // close it
                out.close();
                in.close();
                soc.close();
                send = true;
                //join at every error
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    // start it
    thread.start();

    // join thread
    if (!send) {
        boolean retry = true;
        while(retry)
        try {
            this.thread.join();
            retry = false;
            Log.w(TAG, "sending to server stopped!");
        } catch (InterruptedException e2) {
            Log.w(TAG, "Thread could not be joined");
        }
    }
}

我注意到自 API 5 以来我需要在线程中执行此操作,因此它的工作方式如下。如果玩家触摸屏幕,它会在游戏结束时调用。一切都停止了,数据被发送到服务器。如果他下来它不起作用,我们就会陷入褪色到黑色。 我想我需要类似超时的东西。我用CountDownTimer 尝试过,但这并不能解决问题。

非常感谢!

【问题讨论】:

    标签: android tcp client


    【解决方案1】:

    改变初始化socket的方式,可以设置超时时间。

    Socket s1 = new Socket();
    s1.setSoTimeout(200);
    s1.connect(new InetSocketAddress("192.168.1." + i, 1254), 200);
    

    Add a timeout when creating a new Socket

    【讨论】:

    • 我很抱歉转发我只是没有找到那个解决方案。非常感谢快速帮助它修复它!
    猜你喜欢
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 2013-10-16
    相关资源
    最近更新 更多