我无法从UNIX域套接字读取信息,服务器应用程序是基于Python的,并且我需要实现IPC以作为客户端与Qt应用程序进行通信。服务器应用程序已经过测试,可以与Python客户端应用程序一起使用。这是我在Qt客户端上拥有的内容:
unixsocket.cpp
#include "unixsocket.h"
#include <stdio.h>
UnixSocket::UnixSocket(QObject *parent) :
QObject(parent)
{
this->socket = new QLocalSocket (this);
}
UnixSocket::~UnixSocket(){}
void UnixSocket::Test ()
{
connect (this->socket, SIGNAL(connected()), this, SLOT(connected_callback()));
connect (this->socket, SIGNAL(disconnected()), this, SLOT(disconnected_callback()));
connect (this->socket, SIGNAL(readyRead()), this, SLOT(readyRead_callback()));
connect (this->socket, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten_callback(qint64)));
qDebug() << "Connecting...";
socket->connectToServer(ADAPTER_SOCKET);
if (!socket->waitForConnected(1000))
{
qDebug() << "Error: " << this->socket->errorString();
}
else
{
in.setDevice(socket);
in.setVersion(QDataStream::Qt_5_8);
this->blockSize = 0;
}
}
void UnixSocket::connected_callback()
{
qDebug() << "Connected to " << socket->fullServerName();
}
void UnixSocket::disconnected_callback()
{
qDebug() << "Disconnected!";
}
void UnixSocket::bytesWritten_callback(qint64 bytes)
{
qDebug() << "We wrote: " << bytes;
}
void UnixSocket::readyRead_callback()
{
qDebug() << "Reading...";
qDebug() << "Block Size: " << this->blockSize;
if (this->blockSize == 0) {
// Relies on the fact that QDataStream serializes a quint32 into
// sizeof(quint32) bytes
if (socket->bytesAvailable() < (int)sizeof(quint32))
return;
in >> this->blockSize;
}
if (socket->bytesAvailable() < this->blockSize || in.atEnd())
return;
QString recvd_data;
in >> recvd_data;
qDebug() << recvd_data;
}
unixsocket.h
#ifndef UNIXSOCKET_H
#define UNIXSOCKET_H
#include <QObject>
#include <QAbstractSocket>
#include <QLocalSocket>
#include <QtNetwork>
#include <QIODevice>
#include <QDebug>
#include <QTextStream>
#include <QDataStream>
#define ADAPTER_SOCKET "/opt/adapter/socket"
class UnixSocket: public QObject
{
Q_OBJECT
public:
explicit UnixSocket(QObject *parent = 0);
~UnixSocket();
void Test ();
signals:
public slots:
void connected_callback();
void disconnected_callback();
void bytesWritten_callback (qint64 bytes);
void readyRead_callback();
private:
QLocalSocket *socket;
QDataStream in;
quint32 blockSize;
};
#endif // UNIXSOCKET_H
和 main.cpp 触发课程:
int main(int argc, char* argv[])
{
UnixSocket mUnixSocket;
mUnixSocket.Test();
while (1);
return 1;
}
现在,Unix域套接字连接可以正常工作。因此,我收到“已连接”消息。而且我确定服务器正在异步发送一些数据,但是由于某种原因,我的程序根本不输入readyRead_callback
。我需要有关如何解决此问题的指示。非常感谢您的帮助。
答案 0 :(得分:2)
qt-signals需要生活在Qt事件循环中,并且在您的情况下您没有任何内容,因此它对您不起作用,因此请将代码更改为:
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
UnixSocket mUnixSocket;
mUnixSocket.Test();
return a.exec();
}