网络通信
Qt中进行网络通信时,需要在.pro文件中的 QT 添加 network模块。
注意:Qt应用程序的主线程要用来维护界面,因此不能使用阻塞模式来读取数据。
1、QHostAddress
用来表示网络地址
QHostAddress(const QString &address); 以字符串方式创建网络地址类。
toString 把ip地址转换成字符
特殊地址:
QHostAddress::Null,
QHostAddress::Broadcast, 广播地址
QHostAddress::LocalHost, 本机地址ipv4
QHostAddress::LocalHostIPv6, 本机地址ipv6
QHostAddress::Any, 任意ipv4地址
QHostAddress::AnyIPv6 任意ipv6地址
2、TCP通信
Qt把TCP协议套接字封装成了QTcpSocket类和QTcpServer类。
QTcpServer使用过程:
1、QTcpServer对象
2、设置监听,还需要提供本机地址和端口号
listen(QHostAddress("地址"),端口号);
3、连接新客户端来临的信号
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(new_connect_slot()));
4、在newConnection()信号的槽函数获取新的客户端,会返回一个QTc