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
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");
}
}
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.
617 Uncaught (inpromise) Error on Electron: An object could not be cloned
581 PHP ssh2_scp_send fails to send files as intended
610 GDB gets version error when attempting to debug with the Presense SDK (IDE)
911 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.