我正在为自己设计服务器/客户端系统。我创建了一个从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);
}怎么了?
发布于 2014-09-03 06:29:52
这是QT助理的回答,也许能帮上忙,
qintptr QTcpServer::socketDescriptor() const返回服务器用于侦听传入指令的本机套接字描述符,如果服务器没有侦听,则返回-1。
如果服务器正在使用QNetworkProxy,则返回的描述符可能无法用于本机套接字函数。
https://stackoverflow.com/questions/19892956
复制相似问题