0

在我位于 android 设备中的服务器中,如果客户端数量超过特定数量,则服务器关闭套接字。但是在我的客户端(其他 android 设备)中,我强制关闭。我怎样才能优雅地处理它?这是我客户端上的连接部分:

    serverIpAddress = serverIp.getText().toString();

    if (!serverIpAddress.equals(""))
    {
            try
            {
                 InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                 SocketAddress sockaddr = new InetSocketAddress(serverAddr, 5000);
                 nsocket = new Socket();
                 nsocket.connect(sockaddr);                    
            }catch(Exception e){
                 Log.i("Connect", "Connection Error");
            }

            if (nsocket.isConnected()){
                  score.setText("Your score is " + sc);
                  serverIp.setVisibility(View.GONE);
                  connectPhones.setVisibility(View.GONE);
                  enterIP.setVisibility(View.GONE);
                  Log.i("Connect", "Socket created, streams assigned");
                  Log.i("Connect", "Waiting for inital data..." + nsocket.isConnected());
                  receiveMsg();
            }
4

2 回答 2

0

听起来您用来读取套接字的任何内容都是阻塞读取,并且当套接字关闭并且卡在该读取时会引发异常。确保 read 在 try 块中,并使用 catch/finally 优雅地退出您当时正在做的任何事情。

于 2012-05-29T21:04:21.693 回答
0

继续检查套接字连接是否仍然打开或未在无限循环中使用 isClosed(),当服务器关闭其连接时,isClosed() 变为真,然后显示一条消息或 toast,向用户提供您想要的理由。

于 2012-05-29T19:31:44.577 回答