我的客户端设置如下: 客户端首先发送一个数据包,其中包含要从套接字读取的实际数据的长度。 然后客户端自己发送实际数据。 (在我实际发送数据之前,我正在等待数据包长度。)
我想知道如何在Qt Creator中读取下一个数据包。我得到一个错误说没有找到这样的插槽:MyThread :: readPacket(int)。我做错了什么?
(如果我读错了字节数,则忽略该部分)
我的服务器端代码如下:
#include "thread.h"
#include <QDebug>
#include "DataSetProtos.pb.h"
MyThread::MyThread(qintptr ID, QObject *parent) :
QThread(parent)
{
this->socketDescriptor = ID;
}
void MyThread::run()
{
// thread starts here
qDebug() << " Thread started";
socket = new QTcpSocket();
// set the ID
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
// something's wrong, we just emit a signal
emit error(socket->error());
return;
}
// connect socket and signal
// note - Qt::DirectConnection is used because it's multithreaded
// This makes the slot to be invoked immediately, when the signal is emitted.
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
// We'll have multiple clients, we want to know which is which
qDebug() << socketDescriptor << " Client connected";
// make this thread a loop,
// thread will stay alive so that signal/slot to function properly
// not dropped out in the middle when thread dies
exec();
}
void MyThread::readyRead()
{
// get the information
char* buffer = new char[SIZE];
int iResult= socket->read(buffer, SIZE);
connect(socket,SIGNAL(readyRead()), this, SLOT(readPacket(iResult)), Qt::DirectConnection);
}
void MyThread::readPacket(int bufferLength)
{
char *buffer = new char[bufferLength];
int iResult = socket->read(buffer, bufferLength);
printf("\n Read 2 : %d", iResult);
}
void MyThread::Print(Visualization::PacketData packet)
{
printf("\n\nPacket Name : %s", packet.name());
printf("\n Packet length : %d ", packet.length());
}
void MyThread::disconnected()
{
qDebug() << socketDescriptor << " Disconnected";
socket->deleteLater();
exit(0);
}
我的thread.h文件如下:
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <QTcpSocket>
#include <QDebug>
#include "DataSetProtos.pb.h"
#define SIZE 500
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(qintptr ID, QObject *parent = 0);
void run();
signals:
void error(QTcpSocket::SocketError socketerror);
public slots:
void readyRead();
void readPacket( int bufferLength);
void disconnected();
void Print( Visualization::PacketData packet );
private:
QTcpSocket *socket;
qintptr socketDescriptor;
};
#endif // THREAD_H
答案 0 :(得分:1)
当我们在QT中使用signal
和slot
时,我们需要注意参数。 connect
以下signal
无法使用参数,但您在int
中将SLOT
作为参数。
connect(socket,SIGNAL(readyRead()), this, SLOT(readPacket(iResult)), Qt::DirectConnection);
信号和插槽机制是类型安全的:a的签名 信号必须与接收时隙的签名匹配。
您可以按如下方式连接信号和插槽:
connect(&socket, SIGNAL(readyRead()),this, SLOT(readData()));
您的readData
方法将如下所示
void MyThread :: readData()
{
QString readCurData = socket.readAll();
qDebug() << readCurData;
}
如果您读取这样的套接字数据,那么您也不需要从客户端发送字节数。希望这对你有用。
答案 1 :(得分:1)
正如皮克尔斯先生所说,你对自己非常努力。但是,您不需要一直改变数据格式。您只需要在没有必要时停止尝试使用线程。 Qt中几乎没有任何东西需要使用线程,除了繁重的数据处理或沿着这些线路的东西。绝对不是基本的网络I / O.
我有一个与消息长度前缀的protobufs通信的应用程序。以下是我的onReadyRead实现的要点,更改了一些细节并删除了不必要的内容:
void ProtobufMessageReceiver::onReadyRead()
{
//Some maximum size of a message to protect from malformed
//packets or bugs. This value should be above the size of the largest
//protobuf message you ever expect to receive.
static const uint32_t MAX_ALLOWED_SIZE = 1024 * 1024; //1MB
uint32_t msg_size;
while ( m_socket->bytesAvailable() >= sizeof(msg_size) )
{
m_socket->peek(reinterpret_cast<char*>(&msg_size), sizeof(msg_size));
//OK, we have read in a 32-bit message size, now verify that
//it is valid before we try to read that many bytes on the socket
if ( msg_size > MAX_ALLOWED_SIZE )
{
//You might throw an exception here or do some other error
//handling. Like most Qt code, though, this app doesn't
//use exceptions, so we handle a malformed packet by just
//closing the socket. In a real app you'd probably at least
//want to do some logging here, as this should be a very
//abnormal case and signifies a bug on the sending end.
m_socket->close();
break;
}
//Now check to see if we have that many bytes available to read in.
//If we do, we have at least one full message waiting to process, if not,
//we'll process the message on the next call to onReadyRead.
if ( m_socket->bytesAvailable() >= sizeof(msgSize) + msgSize )
{
m_socket->read(reinterpret_cast<char*>(&msg_size), sizeof(msg_size));
QScopedArrayPointer<char> buffer(new char[msgSize]);
m_socket->read(&buffer[0], msgSize);
processMessage(buffer, msgSize);
}
else
{
break;
}
}
}
现在,processMessage函数将始终传递一个完全有效的protobuf流,可以使用parseFromArray进行解码。 (在这个例子中,我们可能正在使用protobuf Union Type在一个流中交错几种不同的类型)。请注意,因为不能保证每个protobuf消息都会为onReadyRead调用一次,所以在那里使用while循环非常重要。无论您是使用Qt还是其他一些使用套接字的方式,都是如此,因为TCP只是一个字节流,并没有划分消息边界。毕竟,这就是我们首先必须做长度前缀的全部原因。
答案 2 :(得分:0)
你对自己很难。使用JSON对象发送/解析数据包,稍后再次感谢。
他们在Qt得到了很好的支持。据我所知,没有理由不使用它们。
无需发送数据包的长度。您的协议应如下所示:
另请注意,包含数据包ID的enum / struct / class必须与客户端和服务器完全相同。