如何获取SocketChannel收到的数据大小

时间:2015-10-30 18:56:14

标签: java socketchannel

我正在为我的应用程序编写服务器,该服务器必须从客户端获取数据并执行操作。通信是使用SocketChannel完成的,但是有一个问题:我只能从它读取先前指定的字节数(从channel.read(ByteBuffer dst)的javadoc开始)

  

尝试从通道读取最多r个字节,其中r是缓冲区中剩余的字节数

有没有办法获取当前在频道中的数据大小并将其全部读入byte[]

2 个答案:

答案 0 :(得分:0)

there is a problem: i only can read previously specified number of bytes from it

That's not correct.

(as of javadoc for channel.read(ByteBuffer dst))

An attempt is made to read up to r bytes from the channel, where r is the number of bytes remaining in the buffer

You've missed the words 'up to'. There is no problem. If one byte is available, one byte will be read, regardless of the amount of room left in the ByteBuffer.

Is there any way to get size of data, that is currently in the channel and read all it into the byte[]?

That's exactly what happens. The amount of data 'currently in the channel' == the amount of data that will be read provided the room left in the ByteBuffer >= the size of the data in the socket receive buffer, and that will be the value returned by read().

答案 1 :(得分:-1)

我认为没有。你必须自己管理这个。您使用的是序列化对象还是创建了自己的协议?