远程Tcp服务器设备每次发送8个字节的数据,并以相对较快的速度发送(但速度不是很快)。无论如何,我想收到8个字节,并制定了8个字节。但是,我似乎正在接收这些8字节的倍数的bytearrays,我的计数(在代码中)是8个字节的几个倍数,长度从16到120+个字节不等。如何快速接收来自tcp套接字的一个数据包java
检查Wireshark,远程Tcp服务器似乎正确发送出8个字节,而不是合并它们。这表明我读取的套接字太慢,因此将8个字节的间隔重新组合为我,这是我不想要的。一个例子是:
8bytes-8bytes-16bytes-8bytes-8bytes-56bytes。
这是一个时间标记多少数据流英寸只需10毫秒。
(13:44:23.210) 00h 10h 01h 06h FFh 3Ah FFh FFh
(13:44:23.290) 00h 10h 01h 06h FFh 3Fh FFh FFh
(13:44:23.300) 00h 10h 01h 06h FFh 44h FFh FFh
我怎样才能有效地从端口读取尽可能快的速度,同时确保没有8字节数据的倍数?
下面的代码是读取未知大小数据并将其发回到NetworkManager进行进一步处理的段。我尝试过使用不同的流来获得所需的效果,但是两个流都不能确保这一点。
private class Receive extends Thread {
private InputStream inputStream;
private DataInputStream dataInputStream;
private BufferedInputStream bufferedInputStream;
private ByteArrayOutputStream byteArrayOutputStream;
public void run() {
if (DEBUG) Log.d(TAG + " \"" + name + "\"", String.valueOf(getId()) + ":receive run.");
bundle = new Bundle();
buffer = new byte[1024];
try {
bufferedInputStream = new BufferedInputStream(socket.getInputStream());
} catch (IOException ioException) {
Log.d(TAG + " \"" + name + "\"", String.valueOf(getId()) + ":IOException", ioException);
}
while (connected && !closed) {
if (DEBUG) Log.d(TAG + " \"" + name + "\"", String.valueOf(getId()) + ":retry read.");
try {
// socket.setSoTimeout(timeout);
int count = bufferedInputStream.read(buffer);
byteArrayOutputStream = new ByteArrayOutputStream(count);
if (count == -1) {
networkManager.stopTcpNetwork(name);
closed = true;
Log.d(TAG + " \"" + name + "\"", String.valueOf(getId()) + "Connection Lost?!?!");
} else {
if (DEBUG) Log.d(TAG + " \"" + name + "\"", String.valueOf(getId()) + ":call back." + " Count: " + String.valueOf(count));
byteArrayOutputStream.write(buffer, 0, count);
bundle.putByteArray(name, byteArrayOutputStream.toByteArray());
// bundle.putByteArray(name, buffer);
message = networkManager.obtainMessage();
message.what = Messages.MESSAGES_TCP_DATA.getInt();
message.setData(bundle);
networkManager.sendMessage(message);
}
} catch (SocketTimeoutException socketTimeoutException) {
if (DEBUG) Log.d(TAG + " \"" + name + "\"", String.valueOf(getId()) + ":no data yet.");
} catch (Exception exception) {
Log.d(TAG + " \"" + name + "\"", String.valueOf(getId()) + ":Exception", exception);
}
}
}
}
'buffer = new byte [8];'? – greenapps
@greenapps能够有效加速读取操作吗? –
你为什么这么认为?你为什么问? – greenapps