为什么QTcpSocket没有写?我需要刷新它以使其发送我的数据

时间:2016-11-08 21:08:19

标签: c++ qt sockets

我在文档中读到要使用QTcpSocket发送数据包我可以使用ManagementService方法。 但是当我这样做时,我的服务器还没有收到它。我需要致电writeflush发送。

waitForByteWritten

当我调用TCPClient::TCPClient(Client *babel , const std::string &hostname, unsigned short port, QObject *parent) : QObject(parent), client(babel), hostName(hostname), port(port), is_connected(false) { this->tcpSocket = new QTcpSocket(this); connect(this->tcpSocket, SIGNAL(readyRead()),this, SLOT(readMessage())); connect(this->tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError))); connect(this->tcpSocket, SIGNAL(connected()), this, SLOT(connectReady())); connect(this->tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedReady())); } TCPClient::~TCPClient() { } bool TCPClient::initiateService() { this->tcpSocket->connectToHost(this->hostName.c_str(), this->port); this->tcpSocket->waitForConnected(5000); } void TCPClient::connectReady() { this->is_connected = true; } void TCPClient::disconnectedReady() { } bool TCPClient::sendBabelPacket(Protocol::BabelPacket &packet) { if(this->tcpSocket->state() == QAbstractSocket::ConnectedState && is_connected) { std::cout << "writing ... size : " << sizeof(Protocol::BabelPacket) + packet.dataLength<<std::endl; this->tcpSocket->write((const char *)&packet, sizeof(Protocol::BabelPacket) + packet.dataLength); //this->tcpSocket->flush(); return true; } else { std::cout << "socket close" << std::endl; return false; } } void TCPClient::shutDown() { this->tcpSocket->abort(); } void TCPClient::displayError(QAbstractSocket::SocketError socketError) { } void TCPClient::readMessage() { char buffer[sizeof(Protocol::BabelPacket)]; this->tcpSocket->read(buffer, sizeof(Protocol::BabelPacket)); } 时,它会返回正确的字节数。

我在GUI上下文中使用此类,在同一个线程中。

1 个答案:

答案 0 :(得分:8)

QTcpSocket是一个缓冲设备,因此数据不是直接写入,而是写入内部缓冲区。 Documentation州:

  

注意:无法在QIODevice :: Unbuffered模式下打开TCP套接字。

因此,您应该致电flushwaitForBytesWritten以确保传输内容。

它们之间存在差异。 flush尽可能地从内部写缓冲区写入底层网络套接字而不阻塞waitForBytesWritten 阻塞,直到套接字上写入至少一个字节并且已发出bytesWritten()信号。