【发布时间】:2017-01-01 20:14:03
【问题描述】:
我有一个基于 Client/Server 的 Qt 应用程序,使用 QTcpServer 和 QTcpSocket,我设法在客户端和客户端之间建立连接并来回发送一些数据服务器。 客户端向服务器发送多种类型的数据(字符串、整数、文件和实时音频流),并且由于我的服务器实现了单个数据输入 SLOT(readyRead()):
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
- ...
服务器:
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:
// ...
}
}
我不是在寻找一个完整的解决方案,我只是在寻找一些正确方向的指导。
【问题讨论】:
-
您似乎需要发明(或使用现有的)协议,它可以告诉您传输的数据类型。
-
我在网上找不到任何关于如何做到这一点的例子..
-
最起码可以将类型和值打包到消息中,然后在接收端切换类型。
-
你确定你找不到任何东西吗? “我如何创建自己的通信协议”?我得到了很多点击。或者为什么不使用现有协议,例如 HTTP?
-
也许最好单独通过 UDP 提供音频服务。 这是一个想法。对于音频,您可以通过 TCP 发送命令并要求服务器在不同端口上的 UDP 上设置流。
标签: c++ qt client-server qtcpsocket qtcpserver