void MainWindow::on_b_clicked(){ blockSize = 0; tcpSocket->abort(); tcpSocket->connectToHost(ui->host->text(), ui->port->text().toInt()); connect(tcpSocket, SIGNAL(connected()), this, SLOT(sendMsg()));}void MainWindow::sendMsg(){ QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_7); out << (quint16)0; out << QString("hi"); out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); tcpSocket->write(block); while(tcpSocket->bytesToWrite() > 0) { tcpSocket->waitForBytesWritten(); }}
......connect(tcpServer, SIGNAL(newConnection()), this, SLOT(handleConnection()));.....void MainWindow::handleConnection(){ QByteArray block; QDataStream out(&block, QIODevice::ReadWrite); out.setVersion(QDataStream::Qt_4_7); out << (quint16)0; out << QString("ok"); out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); connect(clientConnection, SIGNAL(readyRead()), this, SLOT(slotReadClient())); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); clientConnection->write(block);}void MainWindow::slotReadClient(){ QTcpSocket* pClientSocket = (QTcpSocket*)sender(); QByteArray msg = pClientSocket->readAll(); QString msg_str(msg); this->addLog(msg_str);}
while(tcpSocket->bytesToWrite() > 0) { tcpSocket->waitForBytesWritten(); }
QByteArray block; QDataStream in(&block, QIODevice::ReadOnly); in.setVersion(QDataStream::Qt_4_7); quint16 vers; QString str; in >> vers; in >> str;
QDataStream in(&socket, QIODevice::ReadOnly); in.setVersion(QDataStream::Qt_4_7); quint16 vers; QString str; in >> vers; in >> str;