3

我正在为自己设计服务器/客户端系统。我创建了一个扩展自QTcpServer和定义的类QMap <ClientName, int> sockets来处理连接的客户端。sockets当地图不包含与ClientName新客户端相同的套接字时,客户端可以连接到服务器。因此,当新套接字连接到服务器时,我将客户端存储Pair <ClientName, SocketDescriptor>在 qmap 中。disconnects有了这些解释,当客户端来自服务器时,我应该从 qmap 中删除客户端描述符。因此,我创建插槽void disconnected()并按如下方式实现它:

void MyServer::disconnected()
{
   QTcpSocket* socket = (QTcpSocket*) sender();
   ClientType socketType = ClientTypeNone;
   foreach(ClientType key, _sockets.keys())
   {
      if (sockets.value(key) == socket.socketDescriptor())
      {
         socketType = key;
         break;
      }
   }

   if (socketType != ClientTypeNone)
   {
      sockets.remove(socketType);
   }
}

但是,socket.socketDescriptor是-1,而我在下面的代码中设置了它:

void MyServer::inComingConnection(qintptr socketDescriptor)
{
   QTcpSocket* socket = nextPendingConnection();
   connect(s, SIGNAL(readyRead()), this, SLOT(readyRead());
   connect(s, SIGNAL(disconnected()), this, SLOT(disconnected());
   socket->setSocketDescriptor(socketDescriptor);
}

出了什么问题?

4

2 回答 2

0

这是QT助手的答案,也许有帮助,

qintptr QTcpServer::socketDescriptor() const

返回服务器用于侦听传入指令的本机套接字描述符,如果服务器未在侦听,则返回 -1。

如果服务器正在使用QNetworkProxy,则返回的描述符可能无法与本机套接字函数一起使用。

于 2014-09-03T06:29:52.283 回答
0

我认为您的函数 inComingConnection 应该重命名为incomingConnection 以成为有效的覆盖函数。

但是为什么你不让 Qt 为你设置描述符呢?
根据 Qt 文档:

void QTcpServer::incomingConnection(qintptr socketDescriptor)

...基本实现创建一个 QTcpSocket,设置套接字描述符,然后将 QTcpSocket 存储在未决连接的内部列表中。最后发出 newConnection()。...

这样您就可以简单地使用 addPendingConnection 代替:

void MyServer::addPendingConnection(QTcpSocket *s)
{
   QTcpServer::addPendingConnection(s);
   connect(s, SIGNAL(readyRead()), this, SLOT(readyRead());
   connect(s, SIGNAL(disconnected()), this, SLOT(disconnected());
}
于 2015-05-31T14:33:33.340 回答