QTcpSocket connecting even to no server!
-
hello everyone,
I have an issue with my usage of a QTcpSocket that will connect to no server no matter the adress as long as it is a valide one and regardless of the port :
function used to call the two functions that will actualy connect :
QSettings vmIni("qrc:/VirtualHome.ini"); vmIni.setValue("ServerIP", "127.0.0.1"); vmIni.setValue("ServerPort", 58513); QString ip = vmIni.value("ServerIP").toString(); quint16 port = vmIni.value("ServerPort").toUInt(); qDebug() << "Adress:" << ip << "Port:" << port; if (m_client.bindTo(ip, port)) { if (!m_client.connectTo(ip, port)) qDebug() << "Fail to connect to server."; } else qDebug() << "Fail to bind to server"; qDebug() << "Client connected:" << m_client.isConnected();
and my two functions that actually connects to a supposed server:
bool Client::bindTo(QString adress, quint16 port) { QHostAddress adressToCo; if (adressToCo.setAddress(adress) == true) { m_socket = new QTcpSocket; if (!m_socket->bind(adressToCo, port)) { m_errorMsg = "Bind error to adress: " + adress; qDebug() << "Bind error to adress: " + adress; } } else { m_errorMsg = "Wrong IP address."; qDebug() << "Wrong IP address: " + adress; return false; } qDebug() << "Bind corectly to " + adress; return true; } bool Client::connectTo(QString adress, quint16 port) { QHostAddress adressToCo; adressToCo.setAddress(adress); QObject::connect(m_socket, &QTcpSocket::readyRead, [=] { QString msg = m_socket->readAll(); emit msgRcvd(msg); }); m_socket->connectToHost(adressToCo, port); if (!m_socket->waitForConnected(5000)) { m_errorMsg = m_socket->errorString(); qDebug() << "Error socket:" << m_socket->errorString(); return false; } else if(m_socket->state() != QAbstractSocket::ConnectedState) { m_errorMsg = m_socket->errorString(); qDebug() << "Error socket:" << m_socket->errorString(); return false; } qDebug() << "Connect corectly to " + adress; m_socket->write("writing a useless sentence."); return true; }
so when I put a correct address with any ports I get the output:
Adress: "127.0.0.1" Port: 58513 "Bind corectly to 127.0.0.1" "Connect corectly to 127.0.0.1" Client connected: true
at the end we can see that :
bool Client::isConnected(void) { return m_socket->state() == QAbstractSocket::ConnectedState ? true : false; }
it return true every single times
-
-
@Darta said in QTcpSocket connecting even to no server!:
it return true every single times
And I don't see why not - first you open a port with bind() and then you connect to this opened port with connectTo() which is completely useless and strange but that's not a reason that it will not work.
/edit: You will and must not call bind() on a client socket.
-
@Christian-Ehrlicher thank's very much ^^ It works fine now
-