sendDataToClient(client, "Data not available"); client->disconnectFromHost();
client->disconnectFromHost();
sendDataToClient(client, "Data not available");
void FServer::clientConnected(){ while (hasPendingConnections()) { QTcpSocket *client = nextPendingConnection(); connect(client, SIGNAL(readyRead()), this, SLOT(slotReadDataClient())); connect(client, SIGNAL(disconnected()), this, SLOT(clientDisconnected())); arrayConnections.append(client); qDebug() << "Connect: " << client->peerAddress(); }}
void FServer::slotReadDataClient(){ QTcpSocket *client = qobject_cast<QTcpSocket *>(sender()); QDataStream in(client); in.setVersion(QDataStream::Qt_4_7); while(true) { if(!blockSize) { if(client->bytesAvailable() < sizeof(quint16)) break; in >> blockSize; } if(client->bytesAvailable() < blockSize) break; in >> id_msg; //Обработка мной данных, если они некорректны отправляю отказ и обрубаю соединение. sendDataToClient(client, "Data not available"); client->disconnectFromHost(); blockSize = 0; }}
socket = new QTcpSocket(this); socket->connectToHost("127.0.0.1", 7777); connect(socket, SIGNAL(connected()), this, SLOT(slotConnected())); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError))); connect(socket, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
void MainWindow::slotReadyRead(){ QDataStream in(socket); in.setVersion(QDataStream::Qt_4_7); while (true) { if (!blockSize) { if (socket->bytesAvailable() < sizeof(quint16)) break; in >> blockSize; } if (socket->bytesAvailable() < blockSize) break; in >> id_msg; //Тут разбор сообщения, нечего "военного" blockSize = 0; }}
void FServer::sendDataToClient(qint16 id_msg, QTcpSocket *socket){ QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_7); switch(id_msg) { case 100: { //Формируем сообщение } break; } out.device()->seek(0); out << quint16(block.size() - sizeof(quint16)); socket->write(block);}
C++ (Qt)void FServer::sendDataToClient(qint16 id_msg, QTcpSocket *socket){ ...} ...sendDataToClient(client, "Data not available");
while(true) { if(!m_blockSize) { if(client->bytesAvailable() < sizeof(quint16)) break; in >> m_blockSize; } if(client->bytesAvailable() < m_blockSize) break; if(!m_blockSize) break; //Разбор сообщения m_blockSize = 0; }
if(!m_blockSize) break;