Qt中进行网络通信时,需要在.pro文件中的 QT 添加 network模块。
注意:Qt应用程序的主线程要用来维护界面,因此不能使用阻塞模式来读取数据。
用来表示网络地址
QHostAddress(const QString &address); 以字符串方式创建网络地址类。
toString 把ip地址转换成字符
特殊地址:
QHostAddress::Null,
QHostAddress::Broadcast, 广播地址
QHostAddress::LocalHost, 本机地址ipv4
QHostAddress::LocalHostIPv6, 本机地址ipv6
QHostAddress::Any, 任意ipv4地址
QHostAddress::AnyIPv6 任意ipv6地址
Qt把TCP协议套接字封装成了QTcpSocket类和QTcpServer类。
1、QTcpServer对象
2、设置监听,还需要提供本机地址和端口号
listen(QHostAddress("地址"),端口号);
3、连接新客户端来临的信号
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(new_connect_slot()));
4、在newConnection()信号的槽函数获取新的客户端,会返回一个QTcpSocket对象
把该对象添加容器中,并连接接收数据的槽函数
tcpServer->nextPendingConnection();
clients.push_back(tcpSocket);
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(read_slot()));
5、在readyRead()信号的槽函数中遍历容器,判断有活动的客户端对象,然后接收数据。
if(clients[i]->bytesAvailable())
{
接收数据:
1、readAll(),接收当前缓冲区中的所有数据
2、接收一行数据
qint64 readLine(char *data, qint64 maxlen);
QByteArray readLine(qint64 maxlen = 0);
3、接收指定字节数的数据:
read(char *data, qint64 maxlen);
}
1、创建QTcpSocket对象
2、连接服务器
connectToHost(QHostAddress(ui->lineEdit_ip->text()),
ui->lineEdit_port->text().toShort());
3、连接connected()、disconnected()信号的槽函数
connect(tcpSocket,SIGNAL(connected()),this,SLOT(connected_slot()));
connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(disconnect_slot()));
4、在connected()信号的槽函数中连接readyRead()信号和槽函数
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(read_slot()));
5、发送数据
QString str = ui->lineEdit_msg->text();
tcpSocket->write(str.toStdString().c_str(),str.size()+1);
6、在readyRead()信号的槽函数中接收数据
QByteArray bytebuf = tcpSocket->readAll();
ui->listWidget->addItem(bytebuf);
connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),
this,SLOT(error_slot(QAbstractSocket::SocketError)));
void Widget::error_slot(QAbstractSocket::SocketError error)
{
switch(error)
{
case QAbstractSocket::ConnectionRefusedError:
qDebug("The connection was refused by the peer (or timed out)."); break;
case QAbstractSocket::RemoteHostClosedError:
qDebug("The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent."); break;
case QAbstractSocket::HostNotFoundError:
qDebug("The host address was not found."); break;
case QAbstractSocket::SocketAccessError:
qDebug("The socket operation failed because the application lacked the required privileges."); break;
case QAbstractSocket::SocketResourceError:
qDebug("The local system ran out of resources (e.g., too many sockets)."); break;
case QAbstractSocket::SocketTimeoutError:
qDebug("The socket operation timed out."); break;
case QAbstractSocket::DatagramTooLargeError:
qDebug("The datagram was larger than the operating system's limit (which can be as low as 8192 bytes)."); break;
case QAbstractSocket::NetworkError:
qDebug("An error occurred with the network (e.g., the network cable was accidentally plugged out)."); break;
case QAbstractSocket::AddressInUseError:
qDebug("The address specified to QUdpSocket::bind() is already in use and was set to be exclusive."); break;
case QAbstractSocket::SocketAddressNotAvailableError:
qDebug("The address specified to QUdpSocket::bind() does not belong to the host."); break;
case QAbstractSocket::UnsupportedSocketOperationError:
qDebug("The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support)."); break;
case QAbstractSocket::ProxyAuthenticationRequiredError:
qDebug("The socket is using a proxy, and the proxy requires authentication."); break;
case QAbstractSocket::SslHandshakeFailedError:
qDebug("The SSL/TLS handshake failed, so the connection was closed (only used in QSslSocket) (This value was introduced in 4.4.)"); break;
case QAbstractSocket::UnfinishedSocketOperationError:
qDebug("Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background). (This value was introduced in 4.4.)"); break;
case QAbstractSocket::ProxyConnectionRefusedError:
qDebug("Could not contact the proxy server because the connection to that server was denied (This value was introduced in 4.5.)"); break;
case QAbstractSocket::ProxyConnectionClosedError:
qDebug("The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established) (This value was introduced in 4.5.)"); break;
case QAbstractSocket::ProxyConnectionTimeoutError:
qDebug("The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase. (This value was introduced in 4.5.)"); break;
case QAbstractSocket::ProxyNotFoundError:
qDebug("The proxy address set with setProxy() (or the application proxy) was not found. (This value was introduced in 4.5.)"); break;
case QAbstractSocket::ProxyProtocolError:
qDebug("The connection negotiation with the proxy server because the response from the proxy server could not be understood. (This value was introduced in 4.5.)"); break;
case QAbstractSocket::UnknownSocketError:
qDebug("An unidentified error occurred."); break;
}
}