关闭客户端让服务器崩溃

时间:2013-12-17 16:17:30

标签: android sockets

我在android上有一个简单的客户端和服务器。一切正常,除非我关闭客户端应用程序,然后服务器停止工作,应用程序关闭。

我认为这不是关闭套接字。但是当我在客户端关闭套接字时,服务器仍然停止工作。

我正在服务器上运行一个线程。这是我的服务器代码:

this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();

    }


    @Override
    protected void onStop() {
        super.onStop();
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class ServerThread implements Runnable {

        public void run() {
            Socket socket = null;
            try {
                serverSocket = new ServerSocket(SERVERPORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted()) {

                try {

                    socket = serverSocket.accept();

                    CommunicationThread commThread = new CommunicationThread(socket);
                    new Thread(commThread).start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class CommunicationThread implements Runnable {

        private Socket clientSocket;

        private BufferedReader input;

        public CommunicationThread(Socket clientSocket) {

            this.clientSocket = clientSocket;

            try {

                this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void run() {


            while (!Thread.currentThread().isInterrupted()) {

                try {

                    String read = input.readLine();

                    updateConversationHandler.post(new updateUIThread(read));

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    class updateUIThread implements Runnable {
        private String msg;
        private boolean feedback = false;

        public updateUIThread(String str) {
            msg = str;
        }

        @Override
        public void run() {
            parseCommand();
            if(feedback)
            {
                textFeedback.setText(msg);
                feedback = false;
            }
            else
            {
                textTv.setText(msg);
            }
        }

1 个答案:

答案 0 :(得分:1)

if(msg != null)
   parseCommand();

并在

while(!Thread.currentThread()。isInterrupted()){

        try {

            String read = input.readLine();

            if(read == null)
            {
                clientSocket.close();
                Log.d("Test","SOCKET CLOSED");
                return;
            }

            updateConversationHandler.post(new updateUIThread(read));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }