void MainWindow::readFortune(){//! [9] QDataStream in(tcpSocket); in.setVersion(QDataStream::Qt_4_7); if (blockSize == 0) { if (tcpSocket->bytesAvailable() < (int)sizeof(quint16)) return;//! [8]//! [10] in >> blockSize; } if (tcpSocket->bytesAvailable() < blockSize) return;//! [10] //! [11] QString nextFortune; in >> nextFortune; if (nextFortune == currentFortune) { QTimer::singleShot(0, this, SLOT(requestNewFortune())); return; }//! [11]//! [12] currentFortune = nextFortune;//! [9] //ui->lineEdit->setText(currentFortune); ui->textEdit->setText(currentFortune); ui->pushButton->setEnabled(true);}
void MainWindow::on_Button1_clicked(){ m_ptcpServer = new QTcpServer(this); if (!m_ptcpServer->listen(QHostAddress(ui->lineEdit_2->text()) , ui->lineEdit_3->text().toInt())) { ui->label_3->setText("Server is not working " + m_ptcpServer->errorString()); m_ptcpServer->close(); return; } ui->label_3->setText("Server is working"); connect(m_ptcpServer, SIGNAL(newConnection()),this,SLOT(slotNewConnection()));}void MainWindow::slotNewConnection(){ //QTcpSocket* pClientSocket = m_ptcpServer->nextPendingConnection(); pClientSocket = new QTcpSocket(this); pClientSocket = m_ptcpServer->nextPendingConnection(); connect(pClientSocket, SIGNAL(disconnected()), pClientSocket, SLOT(deleteLater()) ); connect(pClientSocket, SIGNAL(readyRead()), this, SLOT(slotReadClient()) ); ui->label_3->setText("Server Response: Connected!"); //sendToClient(pClientSocket, "Server Response: Connected!"); //sendMessage("Server Response: Connected!");}void MainWindow::on_pushButton_2_clicked(){ //m_ptcpServer = new QTcpServer(this); //FileServer SERVER1("C:/",this); //QTcpSocket* pClientSocket = (QTcpSocket*)sender(); sendMessage(ui->lineEdit->text()); //SERVER1.incomingConnection(m_ptcpServer->socketDescriptor()); ;}void MainWindow::sendMessage(QString MESSAGE){ QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_7); out << (quint16)0; //out << fortunes.at(qrand() % fortunes.size()); //out << ui->lineEdit->text(); out << MESSAGE; out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); /*QTcpSocket *pClientSocket = m_ptcpServer->nextPendingConnection();//tcpServer->nextPendingConnection(); connect(pClientSocket, SIGNAL(disconnected()), pClientSocket, SLOT(deleteLater()));*/ pClientSocket->write(block); pClientSocket->disconnectFromHost(); //clientConnection->write(block); //clientConnection->disconnectFromHost();}
pClientSocket->write(block);pClientSocket->flush();