Qt网络编程

来源:互联网 发布:mysql存储过程execute 编辑:程序博客网 时间:2024/05/21 10:11

1、TCP通信

1.1、TCP客户端

(1)创建TCP客户端

QTcpSocket *tcpClient;

(2)发起连接

tcpClient->connectToHost(hostAddr,port);//有多种重载

(3)数据发送

tcpClient->write();//有多种重载

(4)关闭连接

tcpClient->close();

1.2、TCP服务端

(1)创建TCP服务端

QTcpServer *tcpServer;

(2)启动监听

tcpServer->listen(QHostAddress::Any,port);

(3)处理连接请求

处理QTcpServer::newConnection()信号。当有新连接请求时,创建QTcpSocket*socketRead用于数据接收。

(4)处理数据接收

处理QTcpServer::readReady()信号。当有数据接收事件时,使用socketRead读取数据。

(5)关闭连接

tcpServer->close();

2、UDP通信

2.1、UDP客户端

(1)创建UDP客户端

QUdpSocket *udpSocket;

(2)UDP数据发送

udpSocket->writeDatagram(const char *data, qint64 size, const QHostAddress & address, quint16 port));

(3)关闭连接

udpSocket->close();

2.2、UDP服务端

(1)创建UDP服务端

QUdpSocket *udpServer;

(2)绑定UDP连接

udpServer->bind(address,port);//有多种重载

(3)处理数据接收

处理QUdpSocket::readyRead()信号。使用QUdpSocket::hasPendingDatagrams()检查是否有可读数据,使用QUdpSocket::readDatagram()读取数据。

(4)关闭连接

udpServer->close();


0 0