This is a question when receiving data when communicating with Android sockets.

Asked 2 years ago, Updated 2 years ago, 90 views

I'm trying to get the data through Socket Communication

I am receiving data by calling readLine using Buffered Reader class.

However, when sending data from the server, the data cannot be read without a carriage return.

Assuming that the carriage return is not included when receiving data from the server

Is there any other way to use the readLine function?

android socket socket-communication carriage-return

2022-09-22 21:43

2 Answers

Why don't you do this? Source

String dstAddress;
int dstPort;
String response = "";

try {
    socket = new Socket(dstAddress, dstPort);

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

    int bytesRead;
    InputStream inputStream = socket.getInputStream();

    /*
     * * notice:
     * * inputStream.read() will block if no data return
     */
             while ((bytesRead = inputStream.read(buffer)) != -1){
                 byteArrayOutputStream.write(buffer, 0, bytesRead);
                 response += byteArrayOutputStream.toString("UTF-8");
             }

   } 


2022-09-22 21:43

If you are reading the whole thing, refer to the snippet as follows.

InputStream is = ... ; // Socket
OutputStream out = ...; // To send read data.
byte[] buf = new byte[4096]; //
int nread = 0;
while( ( nread = is.read(buf) ) > 0 ) {
      // If the length of data read from the input stream (socket) is greater than zero...
     out.write(buf,0,nread);
      // Write the 0th to nread of the buffer to out
}

Most I/O to EOF reads.

If the purpose is to copy the top to memory, you can set out to ByteArrayOutputStream.

OutputStream out = new ByteArrayOutputStream();

Please refer to the snippet above and change it to the form you want.


2022-09-22 21:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.