简体   繁体   中英

Handling socket.close() gracefully

In my server located in a android device , if the number number of clients exceeds a specific number then the server close the socket. But in my client(other android device) i get a force close. How can i handle it gracefully? Here is the connect part on my client:

    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();
            }

不断检查套接字连接是否处于打开状态或是否在无限循环中不使用isClosed(),当服务器关闭其连接时,isClosed()为true,然后显示一条消息或祝酒词,向用户说明您想要的原因。

Sounds like whatever you are using to read the socket is a blocking read, and throws an exception when the socket closes and it is stuck at that read. Make sure that read is in a try block, and use the catch/finally to gracefully exit whatever you are doing at that moment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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