本文整理汇总了C++中QTcpSocket::bytesAvailable方法的典型用法代码示例。如果您正苦于以下问题:C++ QTcpSocket::bytesAvailable方法的具体用法?C++ QTcpSocket::bytesAvailable怎么用?C++ QTcpSocket::bytesAvailable使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QTcpSocket
的用法示例。
在下文中一共展示了QTcpSocket::bytesAvailable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: handleClientRead
void CDaemon::handleClientRead()
{
QTcpSocket * socket = qobject_cast<QTcpSocket *>(sender());
while(socket->bytesAvailable() > 8)
{
QDataStream stream(socket);
quint64 size;
stream >> size;
if(socket->bytesAvailable() >= size)
{
QByteArray buffer(socket->read(size));
QDataStream bStream(buffer);
quint8 opcode;
bStream >> opcode;
switch(opcode)
{
case OPCODE_ADD:
handleAdd(bStream); break;
case OPCODE_REMOVE:
handleRemove(bStream); break;
case OPCODE_START:
handleStart(bStream); break;
case OPCODE_STOP:
handleAbort(bStream); break;
case OPCODE_QUEUE:
handleQueue(bStream); break;
default:
qWarning() << "Unhandled packet:" << quint32(opcode); break;
}
}
}
示例2: getSensorTemperature
int MainWindow::getSensorTemperature(){
// Get the server address and port from the settings dialog box
int serverPort = this->dialog->getServerPort(); // get from the dialog box
quint32 serverAddr = this->dialog->getIPAddress(); // from the dialog box
QTcpSocket *tcpSocket = new QTcpSocket(this); // create socket
tcpSocket->connectToHost(QHostAddress(serverAddr), serverPort); // connect
if(!tcpSocket->waitForConnected(1000)){ //wait up to 1s for a connection
statusBar()->showMessage("Failed to connect to server...");
return 1;
}
// Send the message "getTemperature" to the server
tcpSocket->write("getTemperature");
if(!tcpSocket->waitForReadyRead(1000)){ // wait up to 1s for the server
statusBar()->showMessage("Server did not respond...");
return 1;
}
// If the server has sent bytes back to the client
if(tcpSocket->bytesAvailable()>0){
int size = tcpSocket->bytesAvailable(); // how many bytes are ready?
char data[20]; // upper limit of 20 chars
tcpSocket->read(&data[0],(qint64)size); // read the number of bytes rec.
data[size]='\0'; // termintate the string
this->curTemperature = atof(data); // string -> float conversion
cout << "Received the data [" << this->curTemperature << "]" << endl;
}
else{
statusBar()->showMessage("No data available...");
}
return 0; // the on_updateTemperature() slot will update the display
}
示例3: donneesRecues
void FenServeur::donneesRecues()
{
// 1 : on reçoit un paquet (ou un sous-paquet) d'un des clients
// On détermine quel client envoie le message (recherche du QTcpSocket du client)
QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
if (socket == 0) // Si par hasard on n'a pas trouvé le client à l'origine du signal, on arrête la méthode
return;
// Si tout va bien, on continue : on récupère le message
QDataStream in(socket);
if (tailleMessage == 0) // Si on ne connaît pas encore la taille du message, on essaie de la récupérer
{
if (socket->bytesAvailable() < (int)sizeof(quint16)) // On n'a pas reçu la taille du message en entier
return;
in >> tailleMessage; // Si on a reçu la taille du message en entier, on la récupère
}
// Si on connaît la taille du message, on vérifie si on a reçu le message en entier
if (socket->bytesAvailable() < tailleMessage) // Si on n'a pas encore tout reçu, on arrête la méthode
return;
// Si ces lignes s'exécutent, c'est qu'on a reçu tout le message : on peut le récupérer !
QString message;
in >> message;
// 2 : on renvoie le message à tous les clients
envoyerATous(message);
// 3 : remise de la taille du message à 0 pour permettre la réception des futurs messages
tailleMessage = 0;
}
示例4: slotReadClient
void my_server::slotReadClient()
{
QTcpSocket* pClientSocket = (QTcpSocket*)sender();
QDataStream in(pClientSocket);
//in.setVersion(QDataStream::Qt_4_2);
for (;;) {
if (!m_nNextBlockSize) {
if (pClientSocket->bytesAvailable() < sizeof(quint16)) {
break;
}
in >> m_nNextBlockSize;
}
if (pClientSocket->bytesAvailable() < m_nNextBlockSize) {
break;
}
QTime time;
QString str;
in >> time >> str;
QString strMessage =
time.toString() + " " + "Client has sended - " + str;
emit text_to_console(strMessage);
qDebug() << strMessage;
m_nNextBlockSize = 0;
}
}
示例5: slotReadClient
//получаем сообщения от клиента
void InformerTCPServer::slotReadClient()
{
QTcpSocket *pClientSocket = (QTcpSocket*)sender();
QDataStream in(pClientSocket);
in.setVersion(QDataStream::Qt_4_8);
for(;;){
if(!m_nNextBlockSize){
if(pClientSocket->bytesAvailable() < sizeof(quint16))
break;
}
in >> m_nNextBlockSize;
if (pClientSocket->bytesAvailable() < m_nNextBlockSize) {
break;
}
QTime time;
QString str;
in >> time >> str; //записываем сообщения от клиента
//time записываем себе в лог, например
//str пишем туда же
m_nNextBlockSize = 0; //обнуляем счетчик байт
sendToClient(pClientSocket, trUtf8("Сервак ответил")/*отправить сообщение клиенту "бла-бла-бла"*/);
}
}
示例6: donneesRecues
void fenetre_bc::donneesRecues()
{
// On détermine quel client envoie le message (recherche du QTcpSocket du client)
QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
if (socket == 0) // Si on n'a pas trouvé le client à l'origine du signal, on return
return;
// Si non on récupère le message
QDataStream in(socket);
if (tailleMessage == 0) // on recupere la taille du message
{
if (socket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> tailleMessage;
}
// Si on connaît la taille du message, on vérifie si on a reçu le message en entier
if (socket->bytesAvailable() < tailleMessage) // Si on n'a pas encore tout reçu, on arrête la méthode
return;
// on a reçu tout le message : on le recupere
in >>contenu_frame;
liste_BC->append(contenu_frame);
liste_BC->update();
message_is_recieved=true; // on indique qu'un message a été recu
// remise de la taille du message à 0 pour permettre la réception des futurs messages
tailleMessage = 0;
}
示例7: readReceivedData
void CameraTcpServer::readReceivedData()
{
QTcpSocket * client = (QTcpSocket*)sender();
QDataStream in(client);
in.setVersion(QDataStream::Qt_4_0);
if (blockSize_ == 0)
{
if (client->bytesAvailable() < (int)sizeof(quint64))
{
return;
}
in >> blockSize_;
}
if (client->bytesAvailable() < (int)blockSize_)
{
return;
}
std::vector<unsigned char> buf(blockSize_);
in.readRawData((char*)buf.data(), blockSize_);
images_.push_back(cv::imdecode(buf, cv::IMREAD_UNCHANGED));
int queue = Settings::getCamera_9queueSize();
while(queue > 0 && images_.size() > queue)
{
images_.pop_front();
}
blockSize_ = 0;
}
示例8: slotReadClient
void Server::slotReadClient()
{
QTcpSocket* pClientSocket = (QTcpSocket*)sender();
QDataStream in(pClientSocket);
//in.setVersion(QDataStream::Qt_4_8);
for(;;)
{
if (!NextBlockSize)
{
if (pClientSocket->bytesAvailable() < sizeof(quint16)) break;
in >> NextBlockSize;
}
if (pClientSocket->bytesAvailable() < NextBlockSize) break;
QTime time;
QString str;
in >> time >> str;
QString strMessage = time.toString() + " " + "Client has sent - " + str;
//ptxt->append(strMessage);
emit signal_display(strMessage);
NextBlockSize = 0;
str = "Server Response: Recived " + str + "/";
QString *pstr = &str;
sendToClient(pClientSocket, *pstr);
}
}
示例9: receiveMessage
//SLOT : quand un message arrive, le récupère et le traite
void Server::receiveMessage()
{
QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
if (socket == 0)
return;
QDataStream in(socket);
while(1) {
if (tailleMessage == 0) {
if (socket->bytesAvailable() < (int)sizeof(tailleMessage))
return;
in >> tailleMessage;
}
if (socket->bytesAvailable() < tailleMessage)
return;
//récupère le message
QString messageRecu;
in >> messageRecu;
qDebug() <<"Received message: " << messageRecu;
processRequest(messageRecu,socket);
// reset for the next message
tailleMessage = 0;
}
}
示例10: Read
void ServerModel::Read()
{
QTime time;
QString str, message;
QTcpSocket* socket = qobject_cast<QTcpSocket *>(sender());
QDataStream in(socket);
while(true)
{
if(!m_nextBlockSize)
{
if(socket->bytesAvailable() < sizeof(quint16))
break;
in >> m_nextBlockSize;
}
if(socket->bytesAvailable() < m_nextBlockSize)
break;
in >> time >> str;
message = time.toString() + " " + "Client has sent - " + str;
emit SendMessageToMainForm(message);
m_nextBlockSize = 0;
}
}
示例11: slotReadClient
void CGalconServer::slotReadClient()
{
QTcpSocket* pClientSocket = (QTcpSocket*)sender();
QDataStream in(pClientSocket);
in.setVersion(QDataStream::Qt_4_7);
qint16 nextBlockSize = 0;
for (;;)
{
if (pClientSocket->bytesAvailable() < sizeof(quint16))
{
break;
}
in >> nextBlockSize;
if (pClientSocket->bytesAvailable() < nextBlockSize)
{
break;
}
QByteArray str;
in >> str;
ui->tEClient->append(QString(str));
nextBlockSize = 0;
}
}
示例12: onReadyRead
void Graph::onReadyRead()
{
qDebug() << "Graph::readPriborData()";
QTcpSocket *socket = (QTcpSocket *)sender();
const size_t header_size = sizeof(ident_t) + sizeof(int);
while(socket->bytesAvailable() >= header_size)
{
char buf[header_size];
socket->peek(buf, sizeof(buf));
ident_t id = *reinterpret_cast<ident_t *>(buf);
int nvals = *(int *)((ident_t *)buf + 1);
qDebug() << " " << id << nvals << socket->bytesAvailable();
if(socket->bytesAvailable() < nvals*sizeof(Value) + sizeof(id) + sizeof(nvals)) break;
socket->read((char *)&id, sizeof(id));
socket->read((char *)&nvals, sizeof(nvals));
QByteArray data = socket->read(nvals*sizeof(Value));
if((size_t)data.size() < nvals*sizeof(Value)) break;
const Value *v = (const Value *)data.constData();
QVector<Value> vals(nvals);
qCopy(v, v + nvals, vals.begin());
for(Stats::iterator s = stats.begin(); s != stats.end(); ++s)
{
Sourcer *sourcer = s.key();
if(sourcer->ident() == id)
{
if(sourcer->getReliability() == 1)
vals.append(Value(QDateTime::currentDateTime().toTime_t(), sourcer->value()));
s->resize(w, Stat());
fillStats(*s, currentInterval(), vals);
update();
}
}
}
}
示例13: recieveData
void Server::recieveData()
{
QMap<quint32, QTcpSocket *>::const_iterator i = sockets->constBegin();
while (i != sockets->constEnd()) {
QTcpSocket* tcpSocket = i.value();
if (tcpSocket && tcpSocket->bytesAvailable()>0) {
int size = tcpSocket->bytesAvailable();
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);
char *mem = new char[size];
in.readRawData(mem, size);
QString message = QString::fromUtf8(mem, size).trimmed();
delete mem;
emit write_message(tr("Recieved data (size=%1) from %2. Content: \"%3\"").arg(size).arg(tcpSocket->peerAddress().toString()).arg(message));
if (message.startsWith("POST /sms HTTP/")) {
processEventGroup("sms", message, tcpSocket);
} else if (message.startsWith("POST /smsread HTTP/")) {
processEventGroup("smsread", message, tcpSocket);
} else if (message.startsWith("POST /phone HTTP/")) {
processEventGroup("phone", message, tcpSocket);
} else if (message.startsWith("POST /phoneread HTTP/")) {
processEventGroup("phoneread", message, tcpSocket);
} else if (message.startsWith("POST /notify HTTP/")) {
processEventGroup("notify", message, tcpSocket);
} else {
processMessageGroup(message, i.key());
}
}
++i;
}
}
示例14: slotReadClient
// ----------------------------------------------------------------------
void MyServer::slotReadClient()
{
QTcpSocket* pClientSocket = (QTcpSocket*)sender();
QDataStream in(pClientSocket);
in.setVersion(QDataStream::Qt_4_7);
// в цикле проверяем - а все ли данные нам уже пришли? Как только удостоверяемся,что все - продолжаем
for (;;) {
if (!m_nNextBlockSize)
{
if (pClientSocket->bytesAvailable() < (int)sizeof(quint16))
{
break;
}
in >> m_nNextBlockSize;
}
if (pClientSocket->bytesAvailable() < m_nNextBlockSize)
{
break;
}
QTime time = QTime::currentTime();
Sender_socket* pcSocket;
//смотрим, а какой из клиентов отправил нам данные
for (int j = 0; j < 4;j++)
if (clients[j].my_client == pClientSocket)
{
pcSocket = &clients[j];
break;
}
pcSocket->message = new int[32];
qDebug() <<"Message: ";
//записываем полученные данные
for(int j = 0 ; j < 32;j++)
{
in >>pcSocket->message[j];
qDebug()<< pcSocket->message[j]<< " ";
}
QString strMessage =
time.toString() + " " + "Client has sent message.";
m_ptxt->append(strMessage);
m_nNextBlockSize = 0;
}
}
示例15: clientHasData
void CTcpServer::clientHasData(QObject *obj)
{
qDebug() << "Received client data\n";
QTcpSocket *socket = qobject_cast<QTcpSocket *>(obj);
emit dataReceived(socket->readAll());
#if 0
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_4);
while (true)
{
if (clientInfo[socket] == 0)
{
if (socket->bytesAvailable() < (int)sizeof(quint32))
return;
in >> clientInfo[socket];
}
if (socket->bytesAvailable() < clientInfo[socket])
return;
clientTcpReceived(in);
clientInfo[socket] = 0;
}
#endif
}