QSocketNotifier:只能用于以QThread错误启动的线程

时间:2012-12-15 00:16:15

标签: c++ multithreading qt

我正在尝试将QLocalServer用作ipc解决方案。 qt的版本是4.6

这是我的main.cpp:

int main(int argc, const char*argv[]) {  
  QServer test();

  while (true) {
  }
}

这是我的QServer课程:

class QServer : public QObject
{
 Q_OBJECT

public :
 QServer ();

  virtual ~QServer();

private :  
  QLocalServer* m_server;
  QLocalSocket* m_connection;


private slots:
  void socket_new_connection();
};

QServer::QServer()
{
  m_server = new QLocalServer(this);
  if (!m_server->listen("DLSERVER")) {
    qDebug() << "Testing";
    qDebug() << "Not able to start the server";
    qDebug() << m_server->errorString();
    qDebug() << "Server is " << m_server->isListening();
  }

  connect(m_server, SIGNAL(newConnection()),
          this, SLOT(socket_new_connection()));
}

void
QServer::socket_new_connection()
{
  m_connection = m_server->nextPendingConnection();

  connect(clientConnection, SIGNAL(readyRead()),
          this, SLOT(newData(clientConnection)));
}

这一切都在编译,但是在运行时,当我尝试连接newConnection()时,我得到一个QSocketNotifier:只能用于以QThread错误启动的线程。

我试过在QThread中包装这整个东西,但我仍然遇到同样的错误。

任何人都可以解释我做错了什么或者为什么还有线程涉及?

1 个答案:

答案 0 :(得分:11)

错误消息具有误导性。您需要一个Qt事件循环才能使用QSocketNotifier。在您的应用程序中执行此操作的适当方法是创建QApplication(或者如果您不想要任何图形内容,则需要QCoreApplication)。你的主要看起来像:

int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);
    QServer test();
    app.exec();
    return 0;
}

QCoreApplication :: exec()启动事件循环(取代while (true) {}循环)。