《Qt网络编程简介.ppt》由会员分享,可在线阅读,更多相关《Qt网络编程简介.ppt(19页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、1Qt网络编程QIODeviceQAbstractSocketQFileQBufferQUdpSocketQTcpSocketQTcpServerQHostAddress类继承架构图类继承架构图2Qt网络编程QIODevice:是一个抽象类,为Qt中所有提供了打开、关闭、读写的等IO操作方法的类提供一个统一的接口,Qt中具备其接口的类包括QFile、QAbstractSocket、QTcpSocket、QUdpSocket、QBuffer、Qprocess等。操作函数:open(),close()read(),readAll(),readLine()write()Signal:void abo
2、utToClose()void bytesWritten(qint64 bytes)void readChannelFinished()void readyRead()判断函数:bool atEnd()constqint64 bytesAvailable()constqint64 bytesToWrite()constbool canReadLine()const同步操作函数:bool waitForBytesWritten(int msecs)bool waitForReadyRead(int msecs)3Qt网络编程QAbstractSocket是一个抽象类,在QIODevice基础上,
3、为socket提供了公共的接口。操作函数:QAbstractSocket(SocketType socketType,QObject*parent)void connectToHost(const QHostAddress&address,quint16 port,OpenMode openMode=ReadWrite)void disconnectFromHost()信息提取函数:QHostAddress localAddress()constquint16 localPort()constQHostAddress peerAddress()constquint16 peerPort()co
4、nstSocketState state()constSignal:void stateChanged(QAbstractSocket:SocketState socketState)同步操作函数:bool waitForConnected(int msecs=30000)bool waitForDisconnected(int msecs=30000)4Qt网络编程QTcpSocket继承自QAbstractSocket,没有增加接口。QUdpSocket继承自QAbstractSocket,增加了以下UDP特有的接口操作函数:bool bind(const QHostAddress&add
5、ress,quint16 port,BindMode mode)qint64 readDatagram(char*data,qint64 maxSize,QHostAddress*address=0,quint16*port=0)qint64 writeDatagram(const char*data,qint64 size,const QHostAddress&address,quint16 port)qint64 writeDatagram(const QByteArray&datagram,const QHostAddress&host,quint16 port)判断函数:bool ha
6、sPendingDatagrams()constqint64 pendingDatagramSize()const5Qt网络编程QTcpServer提供了TCP监听socket功能。操作函数:bool listen(const QHostAddress&address=QHostAddress:Any,quint16 port=0)setMaxPendingConnections(int numConnections)QTcpSocket*nextPendingConnection()判断函数:bool hasPendingConnections()constbool isListening(
7、)const信息提取函数:QHostAddress serverAddress()constquint16 serverPort()constSignal:void newConnection()同步函数:bool waitForNewConnection(int msec=0,bool*timedOut=0)6Qt网络编程QHostAddress代表IP地址信息,并提供了IP地址和IP字符串相互转换的方法例如:QHostAddress:Any;QHostAddress ip;ip.setAddress(192.168.1.70);7一个小例子:客户端:PC机,发送一字符串给服务器端并显示出来
8、服务器:FriendlyARM开发板,接收客户端发送来的信息并显示目的:建立PC机和开发板的TCP/IP网络通信8客户端:在PC上,利用Qt Creator建立一个client工程,界面如下。9客户端配置client.pro工程文件,加入network支持,如下10客户端11客户端client.cppclient:client(QWidget*parent):QMainWindow(parent),ui(new Ui:client)ui-setupUi(this);/TCP init this-tcpSocket=new QTcpSocket(this);connect(tcpSocket,SIGNAL(connected(),this,SLOT(dataTransfer();connect(tcpSocket,SIGNAL(error(QAbstractSocket:SocketError),this,SLOT(displayError(QAbstractSocket:SocketError);12客户端client.cpp13服务器端在Fedora10中的Qt Creator中新建一个server工程,设计界面如下,用来接收客户端发来的信息。(注意先向server.pro工程配置文件中加入network支持,方法和上面一样)14服务器端:15161718运行结果19