我正在编写一个程序,通过 TCP 连接发送从 OpenCV 窗口捕获的图像,使用 Qt 库设置连接等。
我必须使用函数(如下)来发送文本或字节数组。我遇到的问题是在另一端如何判断传入的数据是纯文本还是包含图像的数组。是否有内置的方法来执行此操作,或者我是否需要在数据的开头放置一个字节以告诉接收方即将到来的数据?我已经将数组长度放在序列化图像数据的开头。
void Screenshot_controller::sendText(std::string textToSend)
{
if(connectionMade)
{
std::string endLine = "\r\n";
textToSend = textToSend + endLine;
const char * textChar = textToSend.c_str();
sendSocket->write(textChar);
sendSocket->flush();
qDebug() << "Text Sent from Server";
}
}
void Screenshot_controller::sendData(QByteArray dataToSend)
{
if(connectionMade)
{
sendSocket->write(dataToSend);
sendSocket->flush();
qDebug() << "Data Sent from Server";
}
}
最佳答案
您需要自己定义协议(protocol),无论是使用字节、字符串、JSON header 还是任何其他方法。 Tcp 套接字将允许您传输数据,但不关心数据是什么;由您来处理。
关于c++ - 在 Qt 中确定 TCP 套接字上的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27152695/