1
我有一個客戶端/服務器基於Qt的應用程序,使用QTcpServer既可並與QTcpSocket多種數據類型,從客戶端到服務器+數據,我能夠做到的連接,發送一些數據來回之間客戶端和服務器。 客戶端發送多種類型的數據服務器(字符串,整數,文件和實時音頻流),並且由於我的服務器impliment單個數據輸入插槽(readyRead()):Qt中,發送流
connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));
我不我知道如何區分所有這些接收到的數據並分別調用服務器中的正確功能。
Example (in the server):
- if I receive string => call function showData(QString data);
- if I receive file => call function saveFile(QFile file);
- if I receive audio stream => play audio stream
- ...
SERVER:
void Server::newClientConnection()
{
QTcpSocket *socket = server->nextPendingConnection();
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
//...
}
void Server::readyRead()
{
QTcpSocket *clientSocket = qobject_cast<QTcpSocket *>(sender());
if (clientSocket == 0) {
return;
}
QDataStream in(clientSocket);
if (sizeMessageClient == 0)
{
if (clientSocket->bytesAvailable() < (int)sizeof(quint16)){
return;
}
in >> sizeMessageClient;
}
if (clientSocket->bytesAvailable() < sizeMessageClient) {
return;
}
sizeMessageClient = 0;
in >> data;
/*
I don't know the type of the received data !!
- if I receive string => call function showData(QString data);
- if I receive file => call function saveFile(QFile file);
- if I receive audio stream => play audio stream
- ...
*/
}
客戶:
Client::Client()
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
sizeMessageServer = 0;
}
void Client::readyRead()
{
QDataStream in(socket);
if (sizeMessageServer == 0)
{
if (socket->bytesAvailable() < (int)sizeof(quint16)) {
return;
}
in >> sizeMessageServer;
}
if (socket->bytesAvailable() < sizeMessageServer) {
return;
}
int messageReceived;
in >> messageReceived;
messageReceived = static_cast<int>(messageReceived);
sizeMessageServer = 0;
switch(messageReceived)
{
case 1:
qDebug() << "send a File";
sendFile();
break;
case 2:
qDebug() << "send a string data";
sendStringData();
break;
case 3:
qDebug() << "stream audio to the server";
streamAudioToServer();
break;
case n:
// ...
}
}
我不是尋找一個完整的解決方案,所有我找的是在正確的方向提供一些指導。
好像你需要創造(或使用現有)*協議*,它可以告訴你你發送什麼樣的數據。 –
我無法在網上找到任何我能做到這一點的例子。 –
至少,您可以將類型和值打包在消息中,然後在類型的接收端交換機上打包。 –