云计算百科
云计算领域专业知识百科平台

QT高阶日记003

网络通信QSocket

网络通信分为TCP/UDP

其他的方式也是由此二类延伸出来的。
QT包括了QTcpSocket,QTcpServer,QUdpServer,QUdpSocket

在项目中要加入
QT +=….. network

一、QTcpServer
方法
close();
errorString();
hasPendingConnections();
isListening();
listen()
maxPendingConnection();
netPendingConnection();
pauseAccepting();
proxy();
resumeAccepting();
serverAddress();
serverError();
serverPort();

setMaxPendingConnection(int num);
setProxy(QNetworkProxy &proxy);
setSocketDescriptor();
socketDescriptor();
waitForNewConnection(int ms,bool timedOut=nullptr);
……
细节还有的话看帮助文档

示例:定义
引用
#include<QTcpServer>

二、QTcpSocket,继承来自QIODevice,同QFile
connectToHost(host,port,openmode,layer);
需要唯一的IP地址和端口去连接服务器。
方法来自Socket底层类
atEnd();
bytesAvailable()
bytesToWrite();
canReadLine();
close();
commitTransaction();
currentReadChannel();
currentWriteChannel();
errorString();
getChar
isOpen
isReadable();
isSequential();
isTextModeEnabled();
isTransactionStarted();
isWritable();
open();
openMode();
peek();
pos();
putChar
read();//c++风格和QT风格的两种读法。
readAll
readChannelCount();
readLine()
reset();
rollbackTransaction();
seek();
setCurrentReadChannel();
setCurrentWriteChannel();
setTextModeEnabled();
size
skip
startTransaction();
ungetChar();
waitForBytesWritten();
waitForReadyRead();
write();//c++风格和QT风格的两种写法。
writeChannelCount();
等等方法和功能函数。
信息号
connected
disconnected
error

QIODevice类的信号
readRead();
readChannelFinished
aboutToClose();
bytesWritten();
channelBytesWritten
channelReadyRead

QIODevice类的方法
readData();
readLineData();
setErrorString();
setOpenMode
writeData();

其他的方法由帮助文件去查询。

重点:
在多线程中。主线程定义的QTcpSocket对象,不能在子线程里使用。只有在子线程里创建的才可以。所以。我们必须在主线程,把连接描述内容传给子线程,在子线程通过该内容创建一个新的QTcpSocket对像。才可以工作。
这样的话,我们需要重写QTcpServer->incomingConnection(qintptr socketDescriptor);方法。
这个方法在有人连接到服务器的时候,自动被QT框架调用的。我们只要在这个函数里,通过信号的方式把这个socketDescriptor内容发送出去。这样的话,我们需要重新作一个类继承QTcpServer类。
用这个类来代替QTcpServer类使用。这样的话,我们就不需要绑定newConnection了。而是帮助我们自定义的信号如myConnection,得到这个发送出来的socketDescriptor信息。传给我们子程序,在子程序里再new 一个QTcpSocket对像。使用socket->setSocketDescriptor(sockDescriptor);的方法。这样的话,就算可以把连接者的信息传给子线程,再创建属于子线程内部的QTcpSocket对像来工作。

这是网络编程中,多线程编程的最要内容。
 

赞(0)
未经允许不得转载:网硕互联帮助中心 » QT高阶日记003
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!