Android使用Socket進行Tcp連線,接收資料不完整
阿新 • • 發佈:2021-06-25
環境:jdk1.8.0_241
Android API 30
Android Studio 4.2
部分程式碼:
/** * 進行與裝置的Tcp通訊 */ public String linkDev(String data, Context context) { // 建立tcp服務 Socket socket = new Socket(); String str = null; if (true) { try { String hostname = new Dao(context).queryIp(); SocketAddress socketAddress = new InetSocketAddress(hostname, 9696); socket.connect(socketAddress, 500); // 獲取socket輸出流物件 OutputStream outputStream = socket.getOutputStream(); // 寫資料 outputStream.write(data.getBytes()); // 與伺服器端互動 InputStream inputStream = socket.getInputStream(); byte[] buf = new byte[10240]; int length = inputStream.read(buf); // 關閉資源 socket.close(); str = new String(buf, 0, length); Log.v("gs1", "length為:" + length); LogLong.d("gs2", "length為:" + length); } catch (SocketTimeoutException e) { Toast.makeText(context, "網路連線超時,請檢查網路環境", Toast.LENGTH_SHORT); Log.v("debug", "錯誤資訊:socket連線超時"); return null; } catch (Exception e) { Log.v("debug", "錯誤資訊gs:" + e.toString()); } } Log.v("返回資料1", str); LogLong.d("返回資料2", str); return str; }
bug描述:APP需要實現和伺服器(使用Json)進行通訊,最初伺服器端返回的資料比較小(1024b左右),通訊正常。
伺服器更新,返回資料達到了 7144b 的大小,APP端在進行接收時只能接受開頭一部分資料(1240~2700b,多次測試接收資料長度不同)。
解決方法:問題的成因是在讀取位元組流的時候資料還未完全接收完,在讀取位元組流
int length = inputStream.read(buf);
的前面加個等待的操作Thread.sleep(400)就可以了;
解決思路://走了不少彎路,之後補上 2021年06月25日 11:48:22