QTcpServer :: incomingConnection(qintptr socketDescriptor)是否可以连接指定的套接字?

时间:2014-01-30 19:04:59

标签: c++ qt sockets qtcpsocket qtcpserver

void server::incomingConnection(qintptr socketDescriptor) {

    qDebug() << "incoming connection";
    connection* new_connection = new connection(this);
    new_connection->set_socket_descriptor(socketDescriptor);

    connect(new_connection, SIGNAL(ready_read()), this, SLOT(ready_read()));
    connect(new_connection, SIGNAL(disconnected()), this, SLOT(disconnected()));

    emit signal_new_connection(new_connection);
} 

服务器类继承自QTcpServer和连接类 有一个QTcpSocket作为成员和一些有关用户的信息 connect(name,ip,id ...)

我的问题是我对new_connection一无所知。我需要知道谁与服务器连接。因为这个原因我想连接回来但是如何?有什么办法吗?或者必须等到我从连接的套接字(用户)收到数据(问候消息)?

1 个答案:

答案 0 :(得分:0)

我只是意外地碰到了这个老线程有同样的问题。我刚刚找到了解决方案,所以我决定在这里发帖以防有人遇到类似的问题。

要获得实际的QTcpSocket(发出readyRead()信号的那个),您可以使用QObject::sender()方法,例如:

void NetServer::onNewConnection() {
    QObject::connect(clientSocket, SIGNAL(readyRead()), this, SLOT(onData()));
}
// ...
void NetServer::onData() {
    QTcpSocket *client = this->server->nextPendingConnection();
    qDebug() << "Received data from" << sender();
    // or
    qDebug() << "Received data from" << this->sender();
    // or even
    qDebug() << "Received data from" << QObject::sender();
}