Qt QTcpServer的使用

来源:互联网 发布:apache 更新 编辑:程序博客网 时间:2024/05/29 09:20

Qt集成许多小工具类,使开发者使用起来十分便利,QTcpServer就是其中一个,我的目的是要构建一个工作在主线程中,不考虑并发情况下的一个小巧的TCP服务,方便构成一个”微服务“,她满足了我的要求。


创建服务很简单。

     m_server = new QTcpServer(this);
     connect(m_server, SIGNAL(newConnection()), this, SLOT(sendFortune()), Qt::DirectConnection);
     if (!m_server->listen(QHostAddress::Any,8003))
     {
         qDebug() << "Test listen Error!";
         m_server->close();
     }
     this->createInsideProc();

上面的代码中创建了一个服务,当有新socket链接进来时,会触发newConnection信号,激发sendFortune槽执行操作。槽中的代码如下:

     QTcpSocket *clientConnection = m_server->nextPendingConnection();
     connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));
     clientConnection->waitForReadyRead(-1);
     QByteArray data = clientConnection->readAll();
     qDebug() << data.data() << "\n";
     ....................
     ....................
     clientConnection->disconnectFromHost();

0 0
原创粉丝点击