简体   繁体   中英

how to read incoming data from socket in android

I create a socket in my android app, when I connect to server I create an InputStream for this socket to read incoming data from server:

socket = new Socket(address, port);

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];

int bytesRead;
InputStream inputStream = socket.getInputStream();
         while ((bytesRead = inputStream.read(buffer)) != -1){
             byteArrayOutputStream.write(buffer, 0, bytesRead);
             response += byteArrayOutputStream.toString("UTF-8");
             // the execution is blocked at this line and does not get out  
             //from the while
         }
  }

After getting the input stream I try to read bytes and fill a String(response) but it blocks within the while -loop when reading all the data from server. This means that the condition in while is not satisfied. I'm sending phrases like this: "hello how are you"

Maybe you should break while loop when \\n arrive or something like that from server. Loop is still waiting for new data to read.

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