Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QAbstractSocket Class

TheQAbstractSocket class provides the base functionality common to all socket types.More...

Header:#include <QAbstractSocket>
Inherits:QIODevice
Inherited By:

QTcpSocket andQUdpSocket

Note: All functions in this class arereentrant.

Public Types

enumNetworkLayerProtocol { IPv4Protocol, IPv6Protocol, UnknownNetworkLayerProtocol }
enumSocketError { ConnectionRefusedError, RemoteHostClosedError, HostNotFoundError, SocketAccessError, ..., UnknownSocketError }
enumSocketOption { LowDelayOption, KeepAliveOption, MulticastTtlOption, MulticastLoopbackOption }
enumSocketState { UnconnectedState, HostLookupState, ConnectingState, ConnectedState, ..., ListeningState }
enumSocketType { TcpSocket, UdpSocket, UnknownSocketType }

Public Functions

QAbstractSocket(SocketType socketType, QObject * parent)
virtual~QAbstractSocket()
voidabort()
voidconnectToHost(const QString & hostName, quint16 port, OpenMode openMode = ReadWrite)
voidconnectToHost(const QHostAddress & address, quint16 port, OpenMode openMode = ReadWrite)
voiddisconnectFromHost()
SocketErrorerror() const
boolflush()
boolisValid() const
QHostAddresslocalAddress() const
quint16localPort() const
QHostAddresspeerAddress() const
QStringpeerName() const
quint16peerPort() const
QNetworkProxyproxy() const
qint64readBufferSize() const
voidsetProxy(const QNetworkProxy & networkProxy)
voidsetReadBufferSize(qint64 size)
boolsetSocketDescriptor(int socketDescriptor, SocketState socketState = ConnectedState, OpenMode openMode = ReadWrite)
voidsetSocketOption(QAbstractSocket::SocketOption option, const QVariant & value)
intsocketDescriptor() const
QVariantsocketOption(QAbstractSocket::SocketOption option)
SocketTypesocketType() const
SocketStatestate() const
boolwaitForConnected(int msecs = 30000)
boolwaitForDisconnected(int msecs = 30000)

Reimplemented Public Functions

virtual boolatEnd() const
virtual qint64bytesAvailable() const
virtual qint64bytesToWrite() const
virtual boolcanReadLine() const
virtual voidclose()
virtual boolisSequential() const
virtual boolwaitForBytesWritten(int msecs = 30000)
virtual boolwaitForReadyRead(int msecs = 30000)
  • 33 public functions inherited fromQIODevice
  • 29 public functions inherited fromQObject

Signals

voidconnected()
voiddisconnected()
voiderror(QAbstractSocket::SocketError socketError)
voidhostFound()
voidproxyAuthenticationRequired(const QNetworkProxy & proxy, QAuthenticator * authenticator)
voidstateChanged(QAbstractSocket::SocketState socketState)

Protected Functions

voidsetLocalAddress(const QHostAddress & address)
voidsetLocalPort(quint16 port)
voidsetPeerAddress(const QHostAddress & address)
voidsetPeerName(const QString & name)
voidsetPeerPort(quint16 port)
voidsetSocketError(SocketError socketError)
voidsetSocketState(SocketState state)

Reimplemented Protected Functions

virtual qint64readData(char * data, qint64 maxSize)
virtual qint64readLineData(char * data, qint64 maxlen)
virtual qint64writeData(const char * data, qint64 size)
  • 5 protected functions inherited fromQIODevice
  • 8 protected functions inherited fromQObject

Protected Slots

voidconnectToHostImplementation(const QString & hostName, quint16 port, OpenMode openMode = ReadWrite)
voiddisconnectFromHostImplementation()

Additional Inherited Members

  • 1 property inherited fromQObject
  • 1 public slot inherited fromQObject
  • 7 static public members inherited fromQObject

Detailed Description

TheQAbstractSocket class provides the base functionality common to all socket types.

QAbstractSocket is the base class forQTcpSocket andQUdpSocket 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 useQAbstractSocket in more or less the same way regardless of the underlying protocol. Internally,QAbstractSocket remembers the address and port passed toconnectToHost(), and functions likeread() andwrite() use these values.

At any time,QAbstractSocket has a state (returned bystate()). The initial state isUnconnectedState. After callingconnectToHost(), the socket first entersHostLookupState. If the host is found,QAbstractSocket entersConnectingState and emits thehostFound() signal. When the connection has been established, it entersConnectedState and emitsconnected(). 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 beConnectedState before reading and writing can occur.

Read or write data by callingread() orwrite(), or use the convenience functionsreadLine() andreadAll().QAbstractSocket also inheritsgetChar(),putChar(), andungetChar() fromQIODevice, which work on single bytes. ThebytesWritten() signal is emitted when data has been written to the socket (i.e., when the client has read the data). Note that Qt does not limit the write buffer size. You can monitor its size by listening to this signal.

ThereadyRead() 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 thereadyRead() 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 toQAbstractSocket's internal read buffer. To limit the size of the read buffer, callsetReadBufferSize().

To close the socket, calldisconnectFromHost().QAbstractSocket entersQAbstractSocket::ClosingState. After all pending data has been written to the socket,QAbstractSocket actually closes the socket, enters QAbstractSocket::ClosedState, and emitsdisconnected(). If you want to abort a connection immediately, discarding all pending data, callabort() instead. If the remote host closes the connection,QAbstractSocket will emit error(QAbstractSocket::RemoteHostClosedError), during which the socket state will still beConnectedState, and then thedisconnected() signal will be emitted.

The port and address of the connected peer is fetched by callingpeerPort() andpeerAddress().peerName() returns the host name of the peer, as passed toconnectToHost().localPort() andlocalAddress() 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;    }

IfwaitForReadyRead() returns false, the connection has been closed or an error has occurred.

Programming with a blocking socket is radically different from programming with a non-blocking socket. A blocking socket doesn't require an event loop and typically leads to simpler code. However, in a GUI application, blocking sockets should only be used in non-GUI threads, to avoid freezing the user interface. See thenetwork/fortuneclient andnetwork/blockingfortuneclient examples for an overview of both approaches.

Note:We discourage the use of the blocking functions together with signals. One of the two possibilities should be used.

QAbstractSocket can be used withQTextStream andQDataStream's stream operators (operator<<() and operator>>()). There is one issue to be aware of, though: You must make sure that enough data is available before attempting to read it using operator>>().

See alsoQFtp,QNetworkAccessManager, andQTcpServer.

Member Type Documentation

enum QAbstractSocket::NetworkLayerProtocol

This enum describes the network layer protocol values used in Qt.

ConstantValueDescription
QAbstractSocket::IPv4Protocol0IPv4
QAbstractSocket::IPv6Protocol1IPv6
QAbstractSocket::UnknownNetworkLayerProtocol-1Other than IPv4 and IPv6

See alsoQHostAddress::protocol().

enum QAbstractSocket::SocketError

This enum describes the socket errors that can occur.

ConstantValueDescription
QAbstractSocket::ConnectionRefusedError0The connection was refused by the peer (or timed out).
QAbstractSocket::RemoteHostClosedError1The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent.
QAbstractSocket::HostNotFoundError2The host address was not found.
QAbstractSocket::SocketAccessError3The socket operation failed because the application lacked the required privileges.
QAbstractSocket::SocketResourceError4The local system ran out of resources (e.g., too many sockets).
QAbstractSocket::SocketTimeoutError5The socket operation timed out.
QAbstractSocket::DatagramTooLargeError6The datagram was larger than the operating system's limit (which can be as low as 8192 bytes).
QAbstractSocket::NetworkError7An error occurred with the network (e.g., the network cable was accidentally plugged out).
QAbstractSocket::AddressInUseError8The address specified toQUdpSocket::bind() is already in use and was set to be exclusive.
QAbstractSocket::SocketAddressNotAvailableError9The address specified toQUdpSocket::bind() does not belong to the host.
QAbstractSocket::UnsupportedSocketOperationError10The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support).
QAbstractSocket::ProxyAuthenticationRequiredError12The socket is using a proxy, and the proxy requires authentication.
QAbstractSocket::SslHandshakeFailedError13The SSL/TLS handshake failed, so the connection was closed (only used inQSslSocket) (This value was introduced in 4.4.)
QAbstractSocket::UnfinishedSocketOperationError11Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background). (This value was introduced in 4.4.)
QAbstractSocket::ProxyConnectionRefusedError14Could not contact the proxy server because the connection to that server was denied (This value was introduced in 4.5.)
QAbstractSocket::ProxyConnectionClosedError15The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established) (This value was introduced in 4.5.)
QAbstractSocket::ProxyConnectionTimeoutError16The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase. (This value was introduced in 4.5.)
QAbstractSocket::ProxyNotFoundError17The proxy address set withsetProxy() (or the application proxy) was not found. (This value was introduced in 4.5.)
QAbstractSocket::ProxyProtocolError18The connection negotiation with the proxy server because the response from the proxy server could not be understood. (This value was introduced in 4.5.)
QAbstractSocket::UnknownSocketError-1An unidentified error occurred.

See alsoQAbstractSocket::error().

enum QAbstractSocket::SocketOption

This enum represents the options that can be set on a socket. If desired, they can be set after having received theconnected() signal from the socket or after having received a new socket from aQTcpServer.

ConstantValueDescription
QAbstractSocket::LowDelayOption0Try to optimize the socket for low latency. For aQTcpSocket this would set the TCP_NODELAY option and disable Nagle's algorithm. Set this to 1 to enable.
QAbstractSocket::KeepAliveOption1Set this to 1 to enable the SO_KEEPALIVE socket option
QAbstractSocket::MulticastTtlOption2Set this to an integer value to set IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.
QAbstractSocket::MulticastLoopbackOption3Set this to 1 to enable the IP_MULTICAST_LOOP (multicast loopback) socket option.

This enum was introduced or modified in Qt 4.6.

See alsoQAbstractSocket::setSocketOption() andQAbstractSocket::socketOption().

enum QAbstractSocket::SocketState

This enum describes the different states in which a socket can be.

ConstantValueDescription
QAbstractSocket::UnconnectedState0The socket is not connected.
QAbstractSocket::HostLookupState1The socket is performing a host name lookup.
QAbstractSocket::ConnectingState2The socket has started establishing a connection.
QAbstractSocket::ConnectedState3A connection is established.
QAbstractSocket::BoundState4The socket is bound to an address and port (for servers).
QAbstractSocket::ClosingState6The socket is about to close (data may still be waiting to be written).
QAbstractSocket::ListeningState5For internal use only.

See alsoQAbstractSocket::state().

enum QAbstractSocket::SocketType

This enum describes the transport layer protocol.

ConstantValueDescription
QAbstractSocket::TcpSocket0TCP
QAbstractSocket::UdpSocket1UDP
QAbstractSocket::UnknownSocketType-1Other than TCP and UDP

See alsoQAbstractSocket::socketType().

Member Function Documentation

QAbstractSocket::QAbstractSocket(SocketType socketType,QObject * parent)

Creates a new abstract socket of typesocketType. Theparent argument is passed toQObject's constructor.

See alsosocketType(),QTcpSocket, andQUdpSocket.

[virtual]QAbstractSocket::~QAbstractSocket()

Destroys the socket.

void QAbstractSocket::abort()

Aborts the current connection and resets the socket. UnlikedisconnectFromHost(), this function immediately closes the socket, discarding any pending data in the write buffer.

See alsodisconnectFromHost() andclose().

[virtual]bool QAbstractSocket::atEnd() const

Reimplemented fromQIODevice::atEnd().

Returns true if no more data is currently available for reading; otherwise returns false.

This function is most commonly used when reading data from the socket in a loop. For example:

// This slot is connected to QAbstractSocket::readyRead()void SocketClass::readyReadSlot() {while (!socket.atEnd()) {QByteArray data= socket.read(100);....     } }

See alsobytesAvailable() andreadyRead().

[virtual]qint64 QAbstractSocket::bytesAvailable() const

Reimplemented fromQIODevice::bytesAvailable().

Returns the number of incoming bytes that are waiting to be read.

See alsobytesToWrite() andread().

[virtual]qint64 QAbstractSocket::bytesToWrite() const

Reimplemented fromQIODevice::bytesToWrite().

Returns the number of bytes that are waiting to be written. The bytes are written when control goes back to the event loop or whenflush() is called.

See alsobytesAvailable() andflush().

[virtual]bool QAbstractSocket::canReadLine() const

Reimplemented fromQIODevice::canReadLine().

Returns true if a line of data can be read from the socket; otherwise returns false.

See alsoreadLine().

[virtual]void QAbstractSocket::close()

Reimplemented fromQIODevice::close().

Closes the I/O device for the socket, disconnects the socket's connection with the host, closes the socket, and resets the name, address, port number and underlying socket descriptor.

SeeQIODevice::close() for a description of the actions that occur when an I/O device is closed.

See alsoabort().

void QAbstractSocket::connectToHost(constQString & hostName,quint16 port,OpenMode openMode = ReadWrite)

Attempts to make a connection tohostName on the givenport.

The socket is opened in the givenopenMode and first entersHostLookupState, then performs a host name lookup ofhostName. If the lookup succeeds,hostFound() is emitted andQAbstractSocket entersConnectingState. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established,QAbstractSocket entersConnectedState and emitsconnected().

At any point, the socket can emiterror() to signal that an error occurred.

hostName may be an IP address in string form (e.g., "43.195.83.32"), or it may be a host name (e.g., "example.com").QAbstractSocket will do a lookup only if required.port is in native byte order.

See alsostate(),peerName(),peerAddress(),peerPort(), andwaitForConnected().

void QAbstractSocket::connectToHost(constQHostAddress & address,quint16 port,OpenMode openMode = ReadWrite)

This is an overloaded function.

Attempts to make a connection toaddress on portport.

[protected slot]void QAbstractSocket::connectToHostImplementation(constQString & hostName,quint16 port,OpenMode openMode = ReadWrite)

Contains the implementation ofconnectToHost().

Attempts to make a connection tohostName on the givenport. The socket is opened in the givenopenMode.

This function was introduced in Qt 4.1.

[signal]void QAbstractSocket::connected()

This signal is emitted afterconnectToHost() has been called and a connection has been successfully established.

Note:On some operating systems the connected() signal may be directly emitted from theconnectToHost() call for connections to the localhost.

See alsoconnectToHost() anddisconnected().

void QAbstractSocket::disconnectFromHost()

Attempts to close the socket. If there is pending data waiting to be written,QAbstractSocket will enterClosingState and wait until all data has been written. Eventually, it will enterUnconnectedState and emit thedisconnected() signal.

See alsoconnectToHost().

[protected slot]void QAbstractSocket::disconnectFromHostImplementation()

Contains the implementation ofdisconnectFromHost().

This function was introduced in Qt 4.1.

[signal]void QAbstractSocket::disconnected()

This signal is emitted when the socket has been disconnected.

Warning: If you need to delete thesender() of this signal in a slot connected to it, use thedeleteLater() function.

See alsoconnectToHost(),disconnectFromHost(), andabort().

SocketError QAbstractSocket::error() const

Returns the type of error that last occurred.

See alsostate() anderrorString().

[signal]void QAbstractSocket::error(QAbstractSocket::SocketError socketError)

This signal is emitted after an error occurred. ThesocketError parameter describes the type of error that occurred.

QAbstractSocket::SocketError is not a registered metatype, so for queued connections, you will have to register it withQ_DECLARE_METATYPE() andqRegisterMetaType().

Note:Signalerror is overloaded in this class. To connect to this one using the function pointer syntax, you must specify the signal type in a static cast, as shown in this example:

connect(abstractSocket,static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error),[=](QAbstractSocket::SocketError socketError){/* ... */ });

See alsoerror(),errorString(), andCreating Custom Qt Types.

bool QAbstractSocket::flush()

This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking. If any data was written, this function returns true; otherwise false is returned.

Call this function if you needQAbstractSocket to start sending buffered data immediately. The number of bytes successfully written depends on the operating system. In most cases, you do not need to call this function, becauseQAbstractSocket will start sending data automatically once control goes back to the event loop. In the absence of an event loop, callwaitForBytesWritten() instead.

See alsowrite() andwaitForBytesWritten().

[signal]void QAbstractSocket::hostFound()

This signal is emitted afterconnectToHost() has been called and the host lookup has succeeded.

Note:Since Qt 4.6.3QAbstractSocket may emit hostFound() directly from theconnectToHost() call since a DNS result could have been cached.

See alsoconnected().

[virtual]bool QAbstractSocket::isSequential() const

Reimplemented fromQIODevice::isSequential().

bool QAbstractSocket::isValid() const

Returns true if the socket is valid and ready for use; otherwise returns false.

Note: The socket's state must beConnectedState before reading and writing can occur.

See alsostate().

QHostAddress QAbstractSocket::localAddress() const

Returns the host address of the local socket if available; otherwise returnsQHostAddress::Null.

This is normally the main IP address of the host, but can beQHostAddress::LocalHost (127.0.0.1) for connections to the local host.

See alsolocalPort(),peerAddress(), andsetLocalAddress().

quint16 QAbstractSocket::localPort() const

Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.

See alsolocalAddress(),peerPort(), andsetLocalPort().

QHostAddress QAbstractSocket::peerAddress() const

Returns the address of the connected peer if the socket is inConnectedState; otherwise returnsQHostAddress::Null.

See alsopeerName(),peerPort(),localAddress(), andsetPeerAddress().

QString QAbstractSocket::peerName() const

Returns the name of the peer as specified byconnectToHost(), or an emptyQString ifconnectToHost() has not been called.

See alsopeerAddress(),peerPort(), andsetPeerName().

quint16 QAbstractSocket::peerPort() const

Returns the port of the connected peer if the socket is inConnectedState; otherwise returns 0.

See alsopeerAddress(),localPort(), andsetPeerPort().

QNetworkProxy QAbstractSocket::proxy() const

Returns the network proxy for this socket. By defaultQNetworkProxy::DefaultProxy is used, which means this socket will query the default proxy settings for the application.

This function was introduced in Qt 4.1.

See alsosetProxy(),QNetworkProxy, andQNetworkProxyFactory.

[signal]void QAbstractSocket::proxyAuthenticationRequired(constQNetworkProxy & proxy,QAuthenticator * authenticator)

This signal can be emitted when aproxy that requires authentication is used. Theauthenticator object can then be filled in with the required details to allow authentication and continue the connection.

Note:It is not possible to use a QueuedConnection to connect to this signal, as the connection will fail if the authenticator has not been filled in with new information when the signal returns.

This function was introduced in Qt 4.3.

See alsoQAuthenticator andQNetworkProxy.

qint64 QAbstractSocket::readBufferSize() const

Returns the size of the internal read buffer. This limits the amount of data that the client can receive before you callread() orreadAll().

A read buffer size of 0 (the default) means that the buffer has no size limit, ensuring that no data is lost.

See alsosetReadBufferSize() andread().

[virtual protected]qint64 QAbstractSocket::readData(char * data,qint64 maxSize)

Reimplemented fromQIODevice::readData().

[virtual protected]qint64 QAbstractSocket::readLineData(char * data,qint64 maxlen)

Reimplemented fromQIODevice::readLineData().

[protected]void QAbstractSocket::setLocalAddress(constQHostAddress & address)

Sets the address on the local side of a connection toaddress.

You can call this function in a subclass ofQAbstractSocket to change the return value of thelocalAddress() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

Note that this function does not bind the local address of the socket prior to a connection (e.g.,QUdpSocket::bind()).

This function was introduced in Qt 4.1.

See alsolocalAddress(),setLocalPort(), andsetPeerAddress().

[protected]void QAbstractSocket::setLocalPort(quint16 port)

Sets the port on the local side of a connection toport.

You can call this function in a subclass ofQAbstractSocket to change the return value of thelocalPort() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

Note that this function does not bind the local port of the socket prior to a connection (e.g.,QUdpSocket::bind()).

This function was introduced in Qt 4.1.

See alsolocalPort(),localAddress(),setLocalAddress(), andsetPeerPort().

[protected]void QAbstractSocket::setPeerAddress(constQHostAddress & address)

Sets the address of the remote side of the connection toaddress.

You can call this function in a subclass ofQAbstractSocket to change the return value of thepeerAddress() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

This function was introduced in Qt 4.1.

See alsopeerAddress(),setPeerPort(), andsetLocalAddress().

[protected]void QAbstractSocket::setPeerName(constQString & name)

Sets the host name of the remote peer toname.

You can call this function in a subclass ofQAbstractSocket to change the return value of thepeerName() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

This function was introduced in Qt 4.1.

See alsopeerName().

[protected]void QAbstractSocket::setPeerPort(quint16 port)

Sets the port of the remote side of the connection toport.

You can call this function in a subclass ofQAbstractSocket to change the return value of thepeerPort() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.

This function was introduced in Qt 4.1.

See alsopeerPort(),setPeerAddress(), andsetLocalPort().

void QAbstractSocket::setProxy(constQNetworkProxy & networkProxy)

Sets the explicit network proxy for this socket tonetworkProxy.

To disable the use of a proxy for this socket, use theQNetworkProxy::NoProxy proxy type:

socket->setProxy(QNetworkProxy::NoProxy);

The default value for the proxy isQNetworkProxy::DefaultProxy, which means the socket will use the application settings: if a proxy is set withQNetworkProxy::setApplicationProxy, it will use that; otherwise, if a factory is set withQNetworkProxyFactory::setApplicationProxyFactory, it will query that factory with typeQNetworkProxyQuery::TcpSocket.

This function was introduced in Qt 4.1.

See alsoproxy(),QNetworkProxy, andQNetworkProxyFactory::queryProxy().

void QAbstractSocket::setReadBufferSize(qint64 size)

Sets the size ofQAbstractSocket's internal read buffer to besize bytes.

If the buffer size is limited to a certain size,QAbstractSocket won't buffer more than this size of data. Exceptionally, a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default.

This option is useful if you only read the data at certain points in time (e.g., in a real-time streaming application) or if you want to protect your socket against receiving too much data, which may eventually cause your application to run out of memory.

OnlyQTcpSocket usesQAbstractSocket's internal buffer;QUdpSocket does not use any buffering at all, but rather relies on the implicit buffering provided by the operating system. Because of this, calling this function onQUdpSocket has no effect.

See alsoreadBufferSize() andread().

bool QAbstractSocket::setSocketDescriptor(int socketDescriptor,SocketState socketState = ConnectedState,OpenMode openMode = ReadWrite)

InitializesQAbstractSocket with the native socket descriptorsocketDescriptor. Returns true ifsocketDescriptor is accepted as a valid socket descriptor; otherwise returns false. The socket is opened in the mode specified byopenMode, and enters the socket state specified bysocketState.

Note: It is not possible to initialize two abstract sockets with the same native socket descriptor.

See alsosocketDescriptor().

[protected]void QAbstractSocket::setSocketError(SocketError socketError)

Sets the type of error that last occurred tosocketError.

See alsosetSocketState() andsetErrorString().

void QAbstractSocket::setSocketOption(QAbstractSocket::SocketOption option, constQVariant & value)

Sets the givenoption to the value described byvalue.

This function was introduced in Qt 4.6.

See alsosocketOption().

[protected]void QAbstractSocket::setSocketState(SocketState state)

Sets the state of the socket tostate.

See alsostate().

int QAbstractSocket::socketDescriptor() const

Returns the native socket descriptor of theQAbstractSocket object if this is available; otherwise returns -1.

If the socket is usingQNetworkProxy, the returned descriptor may not be usable with native socket functions.

The socket descriptor is not available whenQAbstractSocket is inUnconnectedState.

See alsosetSocketDescriptor().

QVariant QAbstractSocket::socketOption(QAbstractSocket::SocketOption option)

Returns the value of theoption option.

This function was introduced in Qt 4.6.

See alsosetSocketOption().

SocketType QAbstractSocket::socketType() const

Returns the socket type (TCP, UDP, or other).

See alsoQTcpSocket andQUdpSocket.

SocketState QAbstractSocket::state() const

Returns the state of the socket.

See alsoerror().

[signal]void QAbstractSocket::stateChanged(QAbstractSocket::SocketState socketState)

This signal is emitted wheneverQAbstractSocket's state changes. ThesocketState parameter is the new state.

QAbstractSocket::SocketState is not a registered metatype, so for queued connections, you will have to register it with Q_REGISTER_METATYPE() andqRegisterMetaType().

See alsostate() andCreating Custom Qt Types.

[virtual]bool QAbstractSocket::waitForBytesWritten(int msecs = 30000)

Reimplemented fromQIODevice::waitForBytesWritten().

bool QAbstractSocket::waitForConnected(int msecs = 30000)

Waits until the socket is connected, up tomsecs milliseconds. If the connection has been established, this function returns true; otherwise it returns false. In the case where it returns false, you can callerror() to determine the cause of the error.

The following example waits up to one second for a connection to be established:

socket->connectToHost("imap",143);if (socket->waitForConnected(1000))qDebug("Connected!");

If msecs is -1, this function will not time out.

Note:This function may wait slightly longer thanmsecs, depending on the time it takes to complete the host lookup.

Note:Multiple calls to this functions do not accumulate the time. If the function times out, the connecting process will be aborted.

See alsoconnectToHost() andconnected().

bool QAbstractSocket::waitForDisconnected(int msecs = 30000)

Waits until the socket has disconnected, up tomsecs milliseconds. If the connection has been disconnected, this function returns true; otherwise it returns false. In the case where it returns false, you can callerror() to determine the cause of the error.

The following example waits up to one second for a connection to be closed:

socket->disconnectFromHost();if (socket->state()==QAbstractSocket::UnconnectedState||        socket->waitForDisconnected(1000))qDebug("Disconnected!");

If msecs is -1, this function will not time out.

See alsodisconnectFromHost() andclose().

[virtual]bool QAbstractSocket::waitForReadyRead(int msecs = 30000)

Reimplemented fromQIODevice::waitForReadyRead().

This function blocks until new data is available for reading and thereadyRead() signal has been emitted. The function will timeout aftermsecs milliseconds; the default timeout is 30000 milliseconds.

The function returns true if thereadyRead() signal is emitted and there is new data available for reading; otherwise it returns false (if an error occurred or the operation timed out).

See alsowaitForBytesWritten().

[virtual protected]qint64 QAbstractSocket::writeData(constchar * data,qint64 size)

Reimplemented fromQIODevice::writeData().

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp