QAbstractSocket

QAbstractSocket 

#include <QAbstractSocket>

 

Public Types

enum BindFlag { ShareAddress, DontShareAddress, ReuseAddressHint, DefaultForPlatform }
flags BindMode
enum NetworkLayerProtocol { IPv4Protocol, IPv6Protocol, AnyIPProtocol, UnknownNetworkLayerProtocol }
enum PauseMode { PauseNever, PauseOnSslErrors }
flags PauseModes
enum SocketError { ConnectionRefusedError, RemoteHostClosedError, HostNotFoundError, SocketAccessError, ..., UnknownSocketError }
enum SocketOption { LowDelayOption, KeepAliveOption, MulticastTtlOption, MulticastLoopbackOption, ..., PathMtuSocketOption }
enum SocketState { UnconnectedState, HostLookupState, ConnectingState, ConnectedState, ..., ListeningState }
enum SocketType { TcpSocket, UdpSocket, SctpSocket, UnknownSocketType }

Public Functions

  QAbstractSocket(QAbstractSocket::SocketType socketType, QObject *parent)
virtual ~QAbstractSocket()
void abort()
bool bind(const QHostAddress &address, quint16 port = 0, QAbstractSocket::BindMode mode = DefaultForPlatform)
bool bind(quint16 port = 0, QAbstractSocket::BindMode mode = DefaultForPlatform)
virtual void connectToHost(const QString &hostName, quint16 port, QIODevice::OpenMode openMode = ReadWrite, QAbstractSocket::NetworkLayerProtocol protocol = AnyIPProtocol)
virtual void connectToHost(const QHostAddress &address, quint16 port, QIODevice::OpenMode openMode = ReadWrite)
virtual void disconnectFromHost()
QAbstractSocket::SocketError error() const
bool flush()
bool isValid() const
QHostAddress localAddress() const
quint16 localPort() const
QAbstractSocket::PauseModes pauseMode() const
QHostAddress peerAddress() const
QString peerName() const
quint16 peerPort() const
QNetworkProxy proxy() const
qint64 readBufferSize() const
virtual void resume()
void setPauseMode(QAbstractSocket::PauseModes pauseMode)
void setProxy(const QNetworkProxy &networkProxy)
virtual void setReadBufferSize(qint64 size)
virtual bool setSocketDescriptor(qintptr socketDescriptor, QAbstractSocket::SocketState socketState = ConnectedState, QIODevice::OpenMode openMode = ReadWrite)
virtual void setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
virtual qintptr socketDescriptor() const
virtual QVariant socketOption(QAbstractSocket::SocketOption option)
QAbstractSocket::SocketType socketType() const
QAbstractSocket::SocketState state() const
virtual bool waitForConnected(int msecs = 30000)
virtual bool waitForDisconnected(int msecs = 30000)

Reimplemented Public Functions

virtual bool atEnd() const override
virtual qint64 bytesAvailable() const override
virtual qint64 bytesToWrite() const override
virtual bool canReadLine() const override
virtual void close() override
virtual bool isSequential() const override
virtual bool waitForBytesWritten(int msecs = 30000) override
virtual bool waitForReadyRead(int msecs = 30000) override
  • 47 public functions inherited from QIODevice
  • 34 public functions inherited from QObject

Signals

void connected()
void disconnected()
void error(QAbstractSocket::SocketError socketError)
void hostFound()
void proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
void stateChanged(QAbstractSocket::SocketState socketState)

Protected Functions

void setLocalAddress(const QHostAddress &address)
void setLocalPort(quint16 port)
void setPeerAddress(const QHostAddress &address)
void setPeerName(const QString &name)
void setPeerPort(quint16 port)
void setSocketError(QAbstractSocket::SocketError socketError)
void setSocketState(QAbstractSocket::SocketState state)

Reimplemented Protected Functions

virtual qint64 readData(char *data, qint64 maxSize) override
virtual qint64 readLineData(char *data, qint64 maxlen) override
virtual qint64 writeData(const char *data, qint64 size) override
  • 5 protected functions inherited from QIODevice
  • 9 protected functions inherited from QObject

Additional Inherited Members

  • 1 property inherited from QObject
  • 1 public slot inherited from QObject
  • 1 public variable inherited from QIODevice
  • 1 public variable inherited from QObject
  • 2 static public members inherited from QIODevice
  • 10 static public members inherited from QObject
  • 2 protected variables inherited from QObject

Detailed Description

The QAbstractSocket class provides the base functionality common to all socket types.

QAbstractSocket is the base class for QTcpSocket and QUdpSocket and contains all common functionality of these two classes. If you need a socket, you have two options:

TCP (Transmission Control Protocol) is a reliable, stream-oriented, connection-oriented transport protocol. UDP (User Datagram Protocol) is an unreliable, datagram-oriented, connectionless protocol. In practice, this means that TCP is better suited for continuous transmission of data, whereas the more lightweight UDP can be used when reliability isn't important.

QAbstractSocket's API unifies most of the differences between the two protocols. For example, although UDP is connectionless, connectToHost() establishes a virtual connection for UDP sockets, enabling you to use QAbstractSocket in more or less the same way regardless of the underlying protocol. Internally, QAbstractSocket remembers the address and port passed to connectToHost(), and functions like read() and write() use these values.

At any time, QAbstractSocket has a state (returned by state()). The initial state is UnconnectedState. After calling connectToHost(), the socket first enters HostLookupState. If the host is found, QAbstractSocket enters ConnectingState and emits the hostFound() signal. When the connection has been established, it enters ConnectedState and emits connected(). If an error occurs at any stage, error() is emitted. Whenever the state changes, stateChanged() is emitted. For convenience, isValid() returns true if the socket is ready for reading and writing, but note that the socket's state must be ConnectedState before reading and writing can occur.

Read or write data by calling read() or write(), or use the convenience functions readLine() and readAll(). QAbstractSocket also inherits getChar(), putChar(), and ungetChar() from QIODevice, which work on single bytes. The bytesWritten() signal is emitted when data has been written to the socket. Note that Qt does not limit the write buffer size. You can monitor its size by listening to this signal.

The readyRead() signal is emitted every time a new chunk of data has arrived. bytesAvailable() then returns the number of bytes that are available for reading. Typically, you would connect the readyRead() signal to a slot and read all available data there. If you don't read all the data at once, the remaining data will still be available later, and any new incoming data will be appended to QAbstractSocket's internal read buffer. To limit the size of the read buffer, call setReadBufferSize().

To close the socket, call disconnectFromHost(). QAbstractSocket enters QAbstractSocket::ClosingState. After all pending data has been written to the socket, QAbstractSocket actually closes the socket, enters QAbstractSocket::UnconnectedState, and emits disconnected(). If you want to abort a connection immediately, discarding all pending data, call abort() instead. If the remote host closes the connection, QAbstractSocket will emit error(QAbstractSocket::RemoteHostClosedError), during which the socket state will still be ConnectedState, and then the disconnected() signal will be emitted.

The port and address of the connected peer is fetched by calling peerPort() and peerAddress(). peerName() returns the host name of the peer, as passed to connectToHost(). localPort() and localAddress() return the port and address of the local socket.

QAbstractSocket provides a set of functions that suspend the calling thread until certain signals are emitted. These functions can be used to implement blocking sockets:

We show an example:

 
      int numRead = 0, numReadTotal = 0;
      char buffer[50];

      forever {
          numRead  = socket.read(buffer, 50);

          // do whatever with array

          numReadTotal += numRead;
          if (numRead == 0 && !socket.waitForReadyRead())
              break;
      }

 

 

 

 

 

 

 

 

 

 

###########################

posted @ 2023-01-10 18:57  西北逍遥  阅读(101)  评论(0编辑  收藏  举报