繁体   English   中英

连接到服务器,但服务器尚未启动Java

[英]connecting to server but server has not started java

我正在创建一个通过套接字连接到服务器(java)的android应用程序。我已经在swing中创建了一个服务器应用程序,其中包含开始按钮,该按钮可以打开我指定的端口。

所以我的问题是,当客户端尝试连接但服务器尚未启动时,我该如何处理情况呢? 而且我还想为客户端创建建议启动服务器的对话框

我已经尝试过此代码,但是它使我的应用程序挂起:

我对此非常困惑!

这是代码:

 try {
        cs = new Socket(IPADD,PORT);
         if(cs.isConnected())
         {   Toast.makeText(ipInfo.this,"Connected",Toast.LENGTH_SHORT).show();
             Intent inst = new Intent(ipInfo.this,homeActivity.class);
             inst.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
             startActivity(inst);
             finish();
        }else {
           Toast.makeText(ipInfo.this,"Server is disconnected\nStart server in desktop",Toast.LENGTH_SHORT).show();
             }
    }catch (IOException e)
     {Toast.makeText(ipInfo.this,e.getMessage(),Toast.LENGTH_SHORT).show();
    }catch (Exception e)
     {Toast.makeText(ipInfo.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}

我认为您必须等待其连接-是否没有回调? 该代码说:

 /**
 * Returns the connection state of the socket.
 * <p>
 * Note: Closing a socket doesn't clear its connection state, which means
 * this method will return <code>true</code> for a closed socket
 * (see {@link #isClosed()}) if it was successfuly connected prior
 * to being closed.
 *
 * @return true if the socket was successfuly connected to a server
 * @since 1.4
 */
public boolean isConnected() {
    // Before 1.3 Sockets were always connected during creation
    return connected || oldImpl;
}

所以isConnected()只是返回一个静态值,该值不太可能实际更改,因此在实例化套接字后立即进行了更改。 Android有很多网络库。 除非您特别需要这样做,否则我建议您使用Retorfit或Volley(尤其是翻新版),或者只是使用OKHTTP客户端并使用它?

您的代码不是永久挂起,它只是在等待超时,因为服务器没有响应,这时您将收到UnknownHostException异常。 捕获并在捕获中显示您的“启动服务器”消息。

try {
    Socket socket = new Socket();
    // 1000 is the timeout
    socket.connect(new InetSocketAddress(IPADD, PORT), 1000);
    Toast.makeText(ipInfo.this,"Connected",Toast.LENGTH_SHORT).show();
    Intent inst = new Intent(ipInfo.this,homeActivity.class);
    inst.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(inst);
    finish();
} catch (IOException e)
    Toast.makeText(ipInfo.this,"Server is disconnected\nStart server in desktop",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
    Toast.makeText(ipInfo.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}

您的套接字代码永远无法工作。 它必须在线程或AsyncTask中执行。 如果您这样做,则无法显示Toast()。

那么你正在做什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM