简体   繁体   English

优雅地处理socket.close()

[英]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. 在我位于android设备中的服务器中,如果客户端数量超过特定数量,则服务器将关闭套接字。 But in my client(other android device) i get a force close. 但是在我的客户端(其他Android设备)中,我被迫关闭。 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. 确保read在try块中,并使用catch / finally退出当前正在执行的操作。

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

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