简体   繁体   中英

Android:socket communication

I am trying to create simple app with android client and java server android client is able to send message to server(java) while when i try to read server reply error:socket closed. line(if((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;
    }
}

Closing the PrintWriter inside the loop doesn't make sense, and closing it before the readLine() call doesn't make sense either. Closing either the input or the output stream of a Socket closes the other stream and the socket.

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