首页| 论坛| 消息

标题:QTcpSocket和QSocketNotifier
作者:ljq1000
日期:2017-05-10 20:32
内容:

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???
...
}[co ..


#1 [ljq1000 05-11 13:51]
去掉_readNotifier,连接TCPSocket::readReady信号就可以了
#2 [weiweiqiao 05-25 10:56]
QTcpSocket每次接收到数据都会emit readyRead信号。你需要将你读取数据的slot方法绑定到此信号。

回复 发表
主题 版块