0

我正在尝试使用 android 客户端和 java 服务器创建简单的应用程序,当我尝试读取服务器回复错误时,android 客户端能够向服务器(java)发送消息:socket 已关闭。行(如果((receiveMessage = receiveRead.readLine())!= null))

public class ClientConnectorTask extends AsyncTask<String, Void, Integer> {
    private Socket client;
    private PrintWriter printwriter;
    protected Integer doInBackground(String...strings) {
        // validate input parameters
        if (strings.length <= 0) {
            return 0;
        }
        // connect to the server and send the message
        try {
            client = new Socket("192.168.1.4", 7777);
            printwriter = new PrintWriter(client.getOutputStream(),true);

            //while(true){
            InputStream istream = client.getInputStream();
            BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

            String  receiveMessage;
            while (true){
            //  printwriter.write(strings[0]);
                printwriter.print(strings[0]);
                printwriter.flush();
                printwriter.close();
                if((receiveMessage = receiveRead.readLine()) != null) //receive from server
                {
                    System.out.println(receiveMessage); // displaying at DOS prompt
                } 
            }
            //}

            //client.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
    protected void onPostExecute(Long result) {
        return;
    }
}
4

1 回答 1

0

关闭PrintWriter循环内部没有意义,在readLine()调用之前关闭它也没有意义。关闭 a 的输入或输出流会Socket关闭另一个流和套接字。

于 2013-03-21T02:37:39.740 回答