Time for action – setting up the client
When the user has provided the server's address and port and has chosen a username, he/she can connect to the server:
void TcpClient::on_connect_clicked() { //... if (m_socket->state() != QAbstractSocket::ConnectedState) { m_socket->connectToHost(ui->address->text(), ui->port->value()); ui->chat->insertPlainText("== Connecting...\n"); } //... }
What just happened?
The private member variable m_socket
holds an instance of QTcpSocket
. If this socket is already connected, nothing happens. Otherwise, the socket is connected to the given address and port by calling connectToHost()
. Besides the obligatory server address and port number, you can pass a third argument to define the mode in which the socket will be opened. For possible values, you can use OpenMode
just like we did for QIODevice
. Since this call is asynchronous, we print a notification to the chat, so that the user is informed that...