QSocket的问题bytesAvailable()和readyread()有什么不同?

yothenlam 2011-10-25 02:12:36
我在tcp已经设置好套接字,使用connect(tcp, SIGNAL(readyRead()), this, SLOT(readTcp()));
后跟一段代码,如下:
while(udt->isConnected())
{
qint64 size = udt->recv(data);//udt之前已经设置定义好了,可以读数据。
tcp->write(data.data(), size);
if (tcp->bytesAvailable() > 0)
{
h = tcp->readLine();
header += h;
if (h.size() == 2)
{
udt->write(header);
header.clear();
}
}

tcp->waitForBytesWritten();
}
然后我定义槽函数readTcp(){QByteArray data = tcp->readAll();}
那么,tcp有数据来的时候,我在readTcp()读取还是在 if (tcp->bytesAvailable() > 0) 使用h = tcp->readLine()下读取??readyRead和bytesAvailable中什么不同
...全文
3481 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
在水一方 2011-11-04
  • 打赏
  • 举报
回复 1
关于socket连接中,最好读取和发送分开来进行,不要写到一个函数里面,这样结构清晰。所以建议你读取数据的操作放到readtcp函数中。
刀刀亮 2011-11-02
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 wzg_j 的回复:]
readyRead()是信号,当数据来临时会发出这个信号
bytesAvailable()是函数,该函数返回当前已经获取的数据的大小
[/Quote]
恩 就是这个意思,readyRead()一旦有数据就会发送,所以你接收数据时接受的数据量是不能确定的,这时候配合bytesAvailable()来控制数据量,当数据达到多少时在进行读取,或者进行处理。这两个一般是配合使用比较好。
就这样好了 2011-11-02
  • 打赏
  • 举报
回复
readyRead()是信号,当数据来临时会发出这个信号
bytesAvailable()是函数,该函数返回当前已经获取的数据的大小
zhh_kv 2011-10-25
  • 打赏
  • 举报
回复
qint64 QIODevice::bytesAvailable () const [virtual]
Returns the number of bytes that are available for reading. This function is commonly used with sequential devices to determine the number of bytes to allocate in a buffer before reading.

Subclasses that reimplement this function must call the base implementation in order to include the size of QIODevices' buffer. Example:

qint64 CustomDevice::bytesAvailable() const
{
return buffer.size() + QIODevice::bytesAvailable();
}

void QIODevice::readyRead () [signal]
This signal is emitted once every time new data is available for reading from the device. It will only be emitted again once new data is available, such as when a new payload of network data has arrived on your network socket, or when a new block of data has been appended to your device.

readyRead() is not emitted recursively; if you reenter the event loop or call waitForReadyRead() inside a slot connected to the readyRead() signal, the signal will not be reemitted (although waitForReadyRead() may still return true).

Note for developers implementing classes derived from QIODevice: you should always emit readyRead() when new data has arrived (do not emit it only because there's data still to be read in your buffers). Do not emit readyRead() in other conditions.

16,240

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧