其他分享
首页 > 其他分享> > c – 如何使用QTcpSocket实例多次使用几秒间隔?

c – 如何使用QTcpSocket实例多次使用几秒间隔?

作者:互联网

我必须多次用QTcpSocket重复相同的请求,间隔几秒钟.
简单的任务,但我无法让它只与一个对象实例一起工作.如何使用相同的QTcpSocket实例再次连接到服务器?
我已经在许多不同的组合中尝试了reset(),resume(),flush(),open()并且它什么都没做.我无法第二次连接ToHost()……

解决方法:

您所要做的就是connectToHost(),使用连接,然后使用disconnectFromHost().而已.没有更多,没有更少.

以下示例说明了客户端和服务器套接字实例的重用.服务器实例保存在仅在必要时增长的池中.它是为Qt 5编写的并使用C 11.

// https://github.com/KubaO/stackoverflown/tree/master/questions/multisocket-22726075
#include <QtNetwork>

class EchoServer : public QTcpServer
{
   QStack<QTcpSocket*> m_pool;
   void incomingConnection(qintptr descr) Q_DECL_OVERRIDE {
      if (m_pool.isEmpty()) {
         auto s = new QTcpSocket(this);
         QObject::connect(s, &QTcpSocket::readyRead, s, [s]{
            s->write(s->readAll());
         });
         QObject::connect(s, &QTcpSocket::disconnected, this, [this, s]{
            m_pool.push(s);
         });
         m_pool.push(s);
      }
      m_pool.pop()->setSocketDescriptor(descr, QTcpSocket::ConnectedState);
   }
public:
   ~EchoServer() { qDebug() << "pool size:" << m_pool.size(); }
};

void setupEchoClient(QTcpSocket & sock)
{
   static const char kByteCount[] = "byteCount";
   QObject::connect(&sock, &QTcpSocket::connected, [&sock]{
      auto byteCount = 64 + qrand() % 65536;
      sock.setProperty(kByteCount, byteCount);
      sock.write(QByteArray(byteCount, '\x2A'));
   });
   QObject::connect(&sock, &QTcpSocket::readyRead, [&sock]{
      auto byteCount = sock.property(kByteCount).toInt();
      if (byteCount) {
         auto read = sock.read(sock.bytesAvailable()).size();
         byteCount -= read;
      }
      if (byteCount <= 0) sock.disconnectFromHost();
      sock.setProperty(kByteCount, byteCount);
   });
}

int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);
   QHostAddress addr("127.0.0.1");
   quint16 port = 5050;

   EchoServer server;
   if (! server.listen(addr, port)) qFatal("can't listen");

   QTcpSocket clientSocket;
   setupEchoClient(clientSocket);

   auto connectsLeft = 20;
   auto connector = [&clientSocket, &addr, port, &connectsLeft]{
      if (connectsLeft--) {
         qDebug() << "connecting" << connectsLeft;
         clientSocket.connectToHost(addr, port);
      } else
         qApp->quit();
   };
   // reconnect upon disconnection
   QObject::connect(&clientSocket, &QTcpSocket::disconnected, connector);
   // initiate first connection
   connector();

   return a.exec();
}

标签:c,tcp,qt,qtcpsocket
来源: https://codeday.me/bug/20190929/1831892.html