• 4395阅读
  • 2回复

[提问]QTcpSocket和QSocketNotifier [复制链接]

上一主题 下一主题
离线ljq1000
 

只看楼主 倒序阅读 楼主  发表于: 2017-05-10
QTcpSocket和QSocketNotifier
QTcpSocket和QSocketNotifier配合使用出现问题,表现为能接收到QSocketNotifier::activated(int)信号,但是从QTcpSocket中读数据时始终返回0。
代码如下:
// class TcpServer : public QTcpServer
void TcpServer::incomingConnection(qintptr socketDescriptor)
{
    QString connName = ...
    TcpConnectionPtr conn(new TcpConnection(connName, socketDescriptor));
    ......
}


TcpConnection::TcpConnection(const QString &name, qintptr sockfd)
    : _name(name),
      _socket(new QTcpSocket(this)),
      _readNotifier(new QSocketNotifier(sockfd, QSocketNotifier::Read, this)),
      _writeNotifier(new QSocketNotifier(sockfd, QSocketNotifier::Write, this)),
      ...
{
    _socket->setSocketDescriptor(sockfd);
    _socket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
    _readNotifier->setEnabled(true);
    _writeNotifier->setEnabled(false);

    connect(_readNotifier, &QSocketNotifier::activated,
            this, &TcpConnection::handleRead,
            Qt::DirectConnection);
    connect(_writeNotifier, &QSocketNotifier::activated,
            this, &TcpConnection::handleWrite,
            Qt::DirectConnection);
    ...
}


void TcpConnection::handleRead(int /*socket*/)
{
    char sbuf[1024];
    qint64 n = _socket->read(sbuf, 1024);
    // n always zero, why???
    ...
}
离线ljq1000

只看该作者 1楼 发表于: 2017-05-11
去掉_readNotifier,连接TCPSocket::readReady信号就可以了
离线weiweiqiao

只看该作者 2楼 发表于: 2017-05-25
QTcpSocket每次接收到数据都会emit readyRead信号。你需要将你读取数据的slot方法绑定到此信号。
Jobs Insanely Great.
快速回复
限100 字节
 
上一个 下一个