简体   繁体   中英

Async socket connection, Client GUI Hangs When Server is Disconnected TCP Communication

I am using Tcp Sockets For Communication Between CLR C++ (Server) to Android(Client) While using .Net For GUI. While the data is communicated and received. Using a Background Worker in C++ Application

if(backgroundworker1->CancellationPending)
                {
                    listenerSocket->Close(); // Listener Socket is Closed
                    netStream->Close(); 
                    serverSocket->Close();
                    serverSocket->Shutdown(SocketShutdown::Both);
                    e->Cancel;
                    break;
                }

While in Android i am using Async Class for Execution and receiving text from socket to a Handler. While in Doinbackground Function i am using this code.

        try
        {

            socket = new Socket(dstAddress, dstPort);
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            do
            {
                try
                {
                    if (!inputStream.ready())
                    {
                        if (message != null)
                            {
                                MainActivity.handler.obtainMessage(0, 0, -1,"Server: " + message).sendToTarget();
                            message = "";
                        }
                    }
                    int num = inputStream.read();
                    message += Character.toString((char) num);
                    Log.e(message,message);
                }
                catch (Exception classNot)
                {
                    Log.e("Client TASK","classnot exception");
                }
            }

            while (!message.equals("bye"));
            inputStream.close();
            socket.close();
        }

I don't understand While am sending the Bye Message from the server and (Backgroundworker1->CancellationPending) All server sockets are closed and Mobile Sockets are closed why is the UI Not Responding? Please Help..

The Problem was in Client in doinbackground Which calls the while loop again hence causing an exception because no data was received in the sockets and causing an exception. Finally added some sleep to the client that after some time the client query the server while if there is no message from the server the client shutdowns and shifted to postexecution function.

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