Android的套接字读取缓冲区大小问题
我有一个网络套接字读的作品在以下情况下罚款:
I have a network Socket read that works fine in below case:
发送方发送为size_t
字节。接收器知道为size_t的值,并使用
Sender sends bytes of size_t
. Receiver knows value of size_t, and uses
do {
long tse = System.currentTimeMillis();
bytesRead = inputStream.read(buffer,current,buffer.length-current));
Log.e("time-spent",String.valueOf(System.currentTimeMillis()-tse));
if(bytesRead >= 0) {
current += bytesRead
}
} while(bytesRead > 0);
其中,缓存
是大小为size_t
。而循环使用,因为读不列入抓取整个数据在一个单一的尝试不同于写呢!
现在,如果发送者每次发送可变数据量,这是不知道接收器,上面的code亘古不出来wuile循环。另外,如果我简单地给 inputStream.read(缓冲区,目前,1024至今));
似乎只读高达1024字节出来循环。
where buffer
is of size size_t
. While loop is used because, read doesnot grab entire data in a single attempt unlike write does!
Now if the sender each time sends variable amount of data,which is not known to receiver, the above code doesnot coming out of wuile loop. Also if i simply give inputStream.read(buffer,current,1024-current));
it seems read only upto 1024 bytes and comes out of loop.
我要接收数据,从 1KB至500KB
的变量数量。我怎样才能用普通的char []数组和TCP套接字(UDP也一样),但不使用NIO的ByteBuffers!
I want to receive variable amount of data ranging from 1kb to 500kb
. How can i using ordinary char[] arrays and TCP sockets(UDP as well) but not using NIO ByteBuffers!
我将设计的应用程序数据包结构为包括长度字段作为要接收的第一个字节(多个)。这将允许接收者了解多少字节来了,相应的计划。
I would design an application packet structure to include the length field as the first byte(s) to be received. This will allow the receiver to understand how many bytes are coming in and plan accordingly.
只要创建看起来像这样的结构:
Simply create a structure that looks like this:
-
长度
:消息的长度被发送 -
载荷
:发送数据是大小长度
的
-
length
: the length of the message being sent. -
payload
: the data being sent that is of sizelength
您可以构建载荷
来也不仅仅是一点点更具描述性的字节[]
;使一个类是序列化
的再presents您的消息。
You can structure payload
to also be a little more descriptive than just byte[]
; make an class that is Serializable
that represents your message.
一旦你有一个良好定义的应用程序包,创建能够理解数据包的接收器的结构的分析器。那么这个解析器将收到的第一个字节或字节,并且知道这些字节重新present的长度
的的有效载荷
。然后它会读载荷
相应。如果载荷
不匹配长度
,该数据包是无效的。
Once you have a well defined application packet, create a parser that understands the structure of the packet for the receiver. This parser will then receive the first byte or bytes and know that those bytes represent the length
of the payload
. It will then read the payload
accordingly. If the payload
doesn't match the length
, the packet is invalid.
如果你不得不简单地使用的char []
,你可以做这样的事情:
If you're forced to simply use char[]
, you can do something like this:
的char []消息= {0×05,'H','E','L','L','O'}; //将0x05长度字段
的注意如何长度
不包括本身的字节数。的
Notice how length
is not including itself in the number of bytes.
这设计是可以在任何平台上用于通信的东西:来自RF收发器的嵌入式系统中TCP通信在Android
This design is something that can be utilized on any platform for communication: from RF transceivers in embedded systems to TCP communication on Android.