QTcpServer提供了newConnection信号, 可以通过connect实现连接槽函数,利用nextPendingConnection
函数获取连接的QTcpSocket * ;也可以继承QTcpServer派生, 复写虚函数incomingConnection(在连接上时,
会自动触发该函数,传参handle);
virtual void incomingConnection(qintptr handle);
通过setSocketDescriptor 函数建立QTcpSocket;
virtual bool setSocketDescriptor(qintptr socketDescriptor, SocketState state = ConnectedState, OpenMode openMode = ReadWrite);
QTcpSocket *pSock = new QTcpSocket; if( ! pSock->setSocketDescriptor(handle) ) { ... }
QTcpSocket有几个继承于 QAbstractSocket, 而QAbstractSocket又继承于QIODevice, 可以看出QtcpSocket可以类似
IO接口一样的进行操作;
virtual void connectToHost(const QString &hostName, quint16 port, OpenMode mode = ReadWrite, NetworkLayerProtocol protocol = AnyIPProtocol); virtual void connectToHost(const QHostAddress &address, quint16 port, OpenMode mode = ReadWrite);
通过connectToHost函数可以连接服务端, 在连接服务端时,将发送信号:
void connected(); void disconnected(); void stateChanged(QAbstractSocket::SocketState);
当socket缓冲区内有数据时,将触发readyRead信号, 利用 bytesAvailable函数可以获取缓冲区内的数据长度, read(length)读取指定长度的数据;