// Example in = new BufferedInputStream(socket.getInputStream()); byte[] buffer = newbyte[1024]; int length = in.read(buffer); Log.i(TAG, "length: " + length);
in = new BufferedInputStream(socket.getInputStream()); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
byte[] buffer = newbyte[1024]; StringBuilder data = new StringBuilder();
int length = in.read(buffer); data.append(new String(buffer, 0, length));
in = new BufferedInputStream(socket.getInputStream()); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
byte[] buffer = newbyte[1024]; StringBuilder data = new StringBuilder();
int length = 0; do { length = in.read(buffer); if (length != -1) { data.append(new String(buffer, 0, length)); } } while (length > 0);
if (data.length() > 0) { // Do something }
// ...
你複製了,按了 build and run,測試到一半發現了另一個問題,也就是文章開頭說的:「長度小於 1024」和「長度大於 1024」的資料擇一正常運作。
in = new BufferedInputStream(socket.getInputStream()); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
byte[] buffer = newbyte[1024]; StringBuilder data = new StringBuilder();
int length = 0; do { length = in.read(buffer); if (length != -1) { data.append(new String(buffer, 0, length)); } if (isReceivedJsonIntact(data.toString())) { break; } } while (length > 0);
/** * Parse JSON each loop to check receiving is the end or not. * * @param message Received JSON in TCP transfer. * @return true if parse not fucked up, aka transfer finished. */ privatebooleanisReceivedJsonIntact(String message){ if (message.isEmpty()) { returnfalse; } try { JSONObject jsonObject = new JSONObject(message); } catch (Exception exception) { returnfalse; } returntrue; }