void FortuneServer::incomingConnection(int socketDescriptor) { QString fortune = fortunes.at(qrand() % fortunes.size()); FortuneThread *thread = new FortuneThread(socketDescriptor, fortune, this); connect(thread, SIGNAL(msgToGUI(QString,int)), SIGNAL(MessageS(QString,int))); connect(thread, SIGNAL(finished()), SLOT(deleteLater())); thread->start(); }
void FortuneThread::run() { tcpSocket = new QTcpSocket(this); // для каждого подключенного клиента свой СОКЕТ if(!tcpSocket->setSocketDescriptor(socketDescriptor)) { emit error(tcpSocket->error()); emit MessageClient(tcpSocket, "<b>SERVER:</b>Error to initialization Socket!",2); } while(true) { if(tcpSocket->state() == QAbstractSocket::UnconnectedState) { tcpSocket->disconnectFromHost(); tcpSocket->waitForDisconnected(); return; // ??????!!!!!!!!!! } if(tcpSocket->waitForReadyRead(3000)) { // .... принимаем данные от клиента } // waitForReadyRead() } // while()}
C++ (Qt)connect(thread, SIGNAL(finished()), SLOT(deleteLater()));
C++ (Qt)connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
C++ (Qt)if(tcpSocket->state() == QAbstractSocket::UnconnectedState) { tcpSocket->disconnectFromHost(); tcpSocket->waitForDisconnected(); return; // ??????!!!!!!!!!! }
QTread *QObject::thread() const{ return d_func()->threadData->thread; // на этой строке вылетала ошибка !!!}
void FortuneThread::run() { headl objHead; IDThr = (int)currentThreadId(); tcpSocket = new QTcpSocket(this); if(!tcpSocket->setSocketDescriptor(socketDescriptor)) { emit error(tcpSocket->error()); emit MessageClient(tcpSocket, "<b>SERVER:</b>Error to initialization Socket!",2); } emit MessageClient(tcpSocket, "<b>SERVER:</b>Client was connected!",2); emit msgToGUI(QTime::currentTime().toString()+" <b>Client</b> " + QString().setNum(numCl) + " CONNECTED!",2); QFile file("MatrixData_" + QString().setNum(IDThr)); if(file.open(QIODevice::WriteOnly)) { while(true) { if(tcpSocket->state() == QAbstractSocket::UnconnectedState) { delete tcpSocket; emit msgToGUI("<b>Client</b> DISCONNECTED!",2); return; } if(tcpSocket->waitForReadyRead(1000)) { if(!flag) // false ; чтение заголовка { timer.start(); retrRead = tcpSocket->read((char*)&objHead,sizeof(objHead)); // читаем переданную стуктуру! if( retrRead == -1) return; if( retrRead == 0) return; } if(tcpSocket->bytesAvailable() != objHead.sizeData) { flag = true; continue; } file.write(tcpSocket->read(objHead.sizeData)); emit MessageClient(tcpSocket, "<b>\nSize file: </b>" + QString().setNum(objHead.sizeData) + " Byte", 2); emit msgToGUI(QTime::currentTime().toString()+" <b>File is sent - </b>" + QString().setNum(timer.elapsed(),10) + " ms",2); flag = false; file.close(); } // waitForReadyRead() } // while() } else { // если нельзя прочитать файл msgToGUI("<b>Error</b> of the determination of the file!",2); return; }}
C++ (Qt)delete tcpSocket;emit msgToGUI("<b>Client</b> DISCONNECTED!",2);
C++ (Qt)tcpSocket = new QTcpSocket(this);
FortuneServer::FortuneServer() : QTcpServer() { fortunes << tr("You've been leading a dog's life. Stay off the furniture.") << tr("You've got to think about tomorrow.") << tr("You will be surprised by a loud noise.") << tr("You will feel hungry again in another hour.") << tr("You might have mail.") << tr("You cannot kill time without injuring eternity.") << tr("Computers are not intelligent. They only think they are."); numCl = 0; }bool FortuneServer::InitializeServer(int port){ QString nP; nP.setNum(port); nPort = port; if (!listen(QHostAddress::Any, nPort)) { QMessageBox::critical(0,"Server Error","Unable to start the server"); return false; } emit MessageS("TCP-Server is listen <b>Port</b> " + nP,2); return true;}void FortuneServer::incomingConnection(int socketDescriptor) { QString fortune = fortunes.at(qrand() % fortunes.size()); FortuneThread *thread = new FortuneThread(socketDescriptor, fortune, this); connect(thread, SIGNAL(msgToGUI(QString,int)), SIGNAL(MessageS(QString,int))); thread->numCl = ++numCl; connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); }// ================================= Thread() ============================================================// конструктор !FortuneThread::FortuneThread(int socketDescriptor, const QString &fortune, QObject *parent) : QThread(parent), socketDescriptor(socketDescriptor), text(fortune), tcpSocket(NULL){ connect(this, SIGNAL(MessageClient(QTcpSocket*,QString,int)),SLOT(sendToClient(QTcpSocket*,QString,int))); flag = false; numCl = 0;}void FortuneThread::run() { headl objHead; IDThr = (int)currentThreadId(); tcpSocket = new QTcpSocket(this); if(!tcpSocket->setSocketDescriptor(socketDescriptor)) { emit error(tcpSocket->error()); emit MessageClient(tcpSocket, "<b>SERVER:</b>Error to initialization Socket!",2); } emit MessageClient(tcpSocket, "<b>SERVER:</b>Client was connected!",2); emit msgToGUI(QTime::currentTime().toString()+" <b>Client</b> " + QString().setNum(numCl) + " CONNECTED!",2); while(!tcpSocket->waitForReadyRead(1)) { if(tcpSocket->state() == QAbstractSocket::UnconnectedState) { emit msgToGUI("<b>Client</b> DISCONNECTED!",2); delete tcpSocket; return; } } QFile file("MatrixData_" + QString().setNum(IDThr)); if(file.open(QIODevice::WriteOnly)) { while(true) { if(tcpSocket->state() == QAbstractSocket::UnconnectedState) { if(file.isOpen()) file.close(); emit msgToGUI("<b>Client</b> DISCONNECTED!",2); delete tcpSocket; return; } if(tcpSocket->waitForReadyRead(1000)) { if(!flag) // false { timer.start(); retrRead = tcpSocket->read((char*)&objHead,sizeof(objHead)); // читаем переданную стуктуру! if( retrRead == -1) return; if( retrRead == 0) return; } if(tcpSocket->bytesAvailable() != objHead.sizeData) { flag = true; continue; } file.write(tcpSocket->read(objHead.sizeData)); emit MessageClient(tcpSocket, "<b>\nSize file: </b>" + QString().setNum(objHead.sizeData) + " Byte", 2); emit msgToGUI(QTime::currentTime().toString()+" <b>File is sent - </b>" + QString().setNum(timer.elapsed(),10) + " ms",2); flag = false; file.close(); } // waitForReadyRead() } // while() } // if() file.open() else { // если нельзя открыть файл msgToGUI("<b>Error</b> of the determination of the file!",2); return; }} // run()void FortuneThread::sendToClient(QTcpSocket* pSocket, QString str, int num) // отправить Клиенту{ QByteArray arrBlock; headl objHeadSendCl; objHeadSendCl.sizeData = str.size(); arrBlock.append((const char*)&objHeadSendCl, sizeof(objHeadSendCl)); arrBlock.append(str); pSocket->write(arrBlock);}
FormServ::FormServ(QWidget *parent) : QDialog(parent){ setupUi(this); // инициализация формы editServ->setFocus(); QRegExp regExp("[0-9]{1,5}"); // ограниченный ввод данных editServ->setValidator(new QRegExpValidator(regExp,this)); connect(butServ, SIGNAL(clicked()), SLOT(lineEd_textPORT())); m_Serv = new FortuneServer; connect(m_Serv, SIGNAL(MessageS(QString,int)), SLOT(slotShowMessage(QString,int)));};void FormServ::lineEd_textPORT(){ bool ok; m_Serv->InitializeServer(editServ->text().toInt(&ok,10));}void FormServ::slotShowMessage(QString mess,int id){ if(id == 2) textEditServ->append(mess); }
C++ (Qt)while(!tcpSocket->waitForReadyRead(1))