I am implementing a server on Android and I am using:
while (!Thread.currentThread().isInterrupted()) {
try {
int r;
String response = "";
while ((r = input.read()) > 0) {
...
}
...
}
I have two issues. If the client sends me a byte of value 0, it is not received by the server.
The second issue is, if the byte value is 128 or more, I keep receiving a value of 65533 or a binary value of 11111101.
Anyone knows how to solve these issues. I am a beginner in networking on JAVA.
If the client sends me a byte of value 0, it is not received by the server.
Yes it is, but you're ignoring it:
while ((r = input.read()) > 0) {
You probably meant:
while ((r = input.read()) > -1) {
The second issue is, if the byte value is 128 or more, I keep receiving a value of 65533 or a binary value of 11111101.
It's not clear what you mean by that, but bear in mind that bytes are signed in Java - the range for a byte is [-128, 127]
.
You should almost certainly not be reading a single byte at a time. Instead, it's usually more appropriate to have a byte array, and call
int bytesRead;
while ((bytesRead = input.read(buffer)) > 0)
Alternatively, if the stream is meant to be text, wrap the input stream in an InputStreamReader
. Don't try to do binary to text conversion yourself - it's fraught with easy-to-miss corner cases.
See more on this question at Stackoverflow