Android Reading From Socket Hangs On Second Read Loop
Solution 1:
The amount of data to be sent/received over a socket based connection is protocol dependend and not known to the TCP/IP stack, but only to the application layer.
The protocol used is developer dependend ... ;-) so coming to your questions:
If I should read only the bytes I am supposed to read, does that mean that I either have to:
- Know in advance the length of the server response?
Yes, this is one possibility.
- or make the server send a code to notify it has finished to send its response?
Also yes, as this is another possibility. Common markers are \n
or \r\n
. The NUL
/'\0'
character also might make sense.
A third option is to prefix each data chunk with a constant number of bytes describing the amount of bytes to come.
Solution 2:
Instead of dealing with bytes, maybe it's simpler handling instances of ad-hoc classes, like - for instance - a Message class:
The server:
// StreamsprotectedObjectInputStreamfromBuffer=null;
protectedObjectOutputStreamtoBuffer=null;
// Listening for a new connectionServerSocketserverConn=newServerSocket(TCP_PORT);
socket = serverConn.accept();
toBuffer = newObjectOutputStream(socket.getOutputStream());
fromBuffer = newObjectInputStream(socket.getInputStream());
// Receiving a new Message objectMessagedata= (Message)fromBuffer.readObject();
The client then sends a message by simply:
// Sending a messageMessagedata=newMessage("Hello");
toBuffer.writeObject(data);
Message can be as complex as needed as long as its members implement Serializable interface.
Post a Comment for "Android Reading From Socket Hangs On Second Read Loop"