Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions | ![]() |
The QAbstractSocket class provides the base functionality common to all socket types. More...
#include <QAbstractSocket>
Inherits QObject and QIODevice.
Inherited by QTcpSocket and QUdpSocket.
Note: All the functions in this class are reentrant.
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 three 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.
By default, QAbstractSocket is non-blocking (asynchronous). This can be changed by calling setBlocking(true). In blocking mode, many functions (notably connectToHost(), read(), write(), and close()) do not return until their operation has completed; in non-blocking mode, all functions except waitForReadyRead() return immediately.
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 the network/fortuneclient and network/blockingfortuneclient examples for an overview of both approaches.
At any time, QAbstractSocket has a state (returned by socketState()). The initial state is Qt::UnconnectedState. After calling connectToHost(), the socket first enters Qt::HostLookupState. If the host is found, QAbstractSocket enters Qt::ConnectingState and emits the hostFound() signal. When the connection has been established, it enters Qt::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.
Read or write data by calling read() or write(), or use the convenience functions readLine() and readAll(). QAbstractSocket also inherits getch(), putch(), and ungetch() from QIODevice, which work on single bytes. For every chunk of data that has been written to the socket, the bytesWritten() signal is emitted.
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 close(). QAbstractSocket enters Qt::ClosingState, then emits closing(). After all pending data has been written to the socket, QAbstractSocket actually closes the socket, enters Qt::ClosedState, and emits closed(). If you want to abort a connection immediately, discarding all pending data, call abort() instead.
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.
Since QAbstractSocket inherits QIODevice, it can be used with QTextStream and QDataStream's stream operators (operator<<() and operator>>()). There is one issue to be aware of, though: In non-blocking mode, you must make sure that enough data is available before attempting to read it using operator>>().
See also QFtp, QHttp, and QTcpServer.
Creates a new abstract socket of type socketType. The parent argument is passed to QObject's constructor.
See also socketType(), QTcpSocket, and QUdpSocket.
Destroys the socket.
Aborts the current connection and resets the socket. Unlike close(), this function immediately closes the socket, clearing any pending data in the write buffer.
See also close().
Always returns 0.
Reimplemented from QIODevice.
Returns the number of incoming bytes that are waiting to be read.
See also bytesToWrite() and read().
Returns the number of bytes that are waiting to be written. The bytes are written when control goes back to the event loop or when flush() is called.
See also bytesAvailable() and flush().
This signal is emitted when a payload of data has been written to the network. The numBytes parameter specifies how many bytes were written.
See also write() and bytesToWrite().
Returns true if a line of data can be read from the socket; otherwise returns false.
See also readLine().
Attempts to close the socket. If there is pending data waiting to be written, QAbstractSocket will enter Qt::ClosingState and wait until all data has been written. Eventually, it will enter Qt::ClosedState and emit the closed() signal.
Reimplemented from QIODevice.
See also abort().
This signal is emitted when the connection has been closed.
See also connectToHost() and close().
This signal is emitted when the connection is closing, before any pending data has been written to the network.
See also closed().
Attempts to make a connection to hostName on port port. Returns true if the connection has been established; otherwise returns false.
QAbstractSocket first enters Qt::HostLookupState, then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters Qt::ConnectingState. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters Qt::ConnectedState and emits connected().
At any point, the socket can emit error() 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., "www.trolltech.com"). QAbstractSocket will do a lookup only if required. port is in native byte order.
See also socketState(), peerName(), peerAddress(), and peerPort().
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Attempts to make a connection to address on port port.
This signal is emitted after connectToHost() has been called and a connection has been successfully established.
See also connectToHost() and connectionClosed().
This signal is emitted after an error occurred. The socketError parameter is a Qt::SocketError value.
See also socketError() and errorString().
Returns the type of error that last occurred as a human-readable string.
See also socketError().
Writes any pending outgoing data to the socket.
If the socket is in blocking mode, this function blocks until all data has been written or until the timeout has expired; otherwise, the function writes as much as it can without blocking.
Reimplemented from QIODevice.
See also setBlocking().
This signal is emitted after connectToHost() has been called and the host lookup has succeeded.
See also connected().
Returns true if the socket is blocking; otherwise returns false.
See also setBlocking().
Returns true if the socket is valid and ready for use; otherwise returns false.
See also socketState().
Returns the host address of the local socket if available; otherwise returns QHostAddress::Null.
This is normally the main IP address of the host, but can be QHostAddress::LocalHost (127.0.0.1) for connections to the local host.
See also localPort() and peerAddress().
Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.
See also localAddress() and peerPort().
Returns the address of the connected peer if the socket is in Qt::ConnectedState; otherwise returns QHostAddress::Null.
See also peerName(), peerPort(), and localAddress().
Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called.
See also peerAddress() and peerPort().
Returns the port of the connected peer if the socket is in Qt::ConnectedState; otherwise returns 0.
See also peerAddress() and localPort().
Reads at most maxSize bytes from the socket into data. Returns the number of bytes read, or -1 if an error occurred.
If the socket is in blocking mode and no data is available (i.e., bytesAvailable() returns 0), this function will block until data is available or until the timeout expires.
Reimplemented from QIODevice.
See also readLine(), readAll(), getch(), write(), and setBlocking().
Returns the size of the internal read buffer. This limits the amount of data that the client can receive before you call read() or readAll().
A read buffer size of 0 (the default) means that the buffer has no size limit, ensuring that no data is lost.
See also setReadBufferSize() and read().
Reads a '\n'-terminated line of ASCII data from the socket and returns it as a QByteArray (including the '\n'). If no line can be read, it returns an empty QByteArray.
If the socket is in blocking mode, this function will block until a whole line can be read or until the timeout expires.
Reimplemented from QIODevice.
See also canReadLine() and setBlocking().
This signal is emitted every time there is new incoming data.
Bear in mind that new incoming data is only reported once; if you do not read any data, this class buffers the data and you can read it later, but no signal is emitted until new data arrives. A good practice is to read all data in the slot connected to this signal unless you need to receive more data to be able to process it.
See also read(), readAll(), readLine(), and bytesAvailable().
If blocking is true, sets the socket to blocking mode and the timeout to msec milliseconds (the default timeout is 30 seconds); otherwise, sets the socket to non-blocking mode (msec is ignored).
In blocking mode, connectToHost(), read(), write(), readLine(), getch(), putch(), and close() suspend the program's execution until their task has been completed or until the timeout has expired. For example:
QTcpSocket socket; socket.setBlocking(true); if (socket.connectToHost("imap", 143)) { qDebug("Connected!"); } else { qDebug("Unable to connect: %s", socket.errorString().latin1()); }
Blocking mode is the only option in applications that do not have an event loop.
See also isBlocking() and waitForReadyRead().
Sets the size of QAbstractSocket's internal read buffer to be size 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.
See also readBufferSize() and read().
Initializes QAbstractSocket with the native socket descriptor socketDescriptor. Returns true if socketDescriptor is accepted as a valid socket descriptor; otherwise returns false. QAbstractSocket enters the socket state specified by socketState.
See also socketDescriptor().
Same as bytesAvailable().
Reimplemented from QIODevice.
Returns the native socket descriptor of QAbstractSocket if this is available; otherwise returns -1.
The socket descriptor is not available when QAbstractSocket is in Qt::UnconnectedState.
See also setSocketDescriptor().
Returns the type of error that last occurred.
See also socketState() and errorString().
Returns the state of the socket.
See also socketError().
Returns the socket type (TCP, UDP, or other).
See also QTcpSocket and QUdpSocket.
This signal is emitted whenever QAbstractSocket's state changes. The socketState parameter is a Qt::SocketState value.
See also socketState().
Waits until there is data available for reading, up to msecs milliseconds. Returns true if there is data available; otherwise returns false. In the case where it returns false, you can call socketError() to determine the cause of the error.
This function is blocking regardless of whether setBlocking() was called or not, but is most commonly used in blocking mode to achieve a semi-non-blocking behavior.
The following example waits up to one second for a line of data to arrive:
if (socket->waitForReadyRead(1000) && socket->canReadLine()) { QByteArray line = socket->readLine(); qDebug("Read line: %s", line.ascii()); }
See also setBlocking() and readyRead().
Writes size bytes to the socket from data. Returns the number of bytes written, or -1 if an error occurred.
If the socket is in blocking mode, this function will block until all the data is written to the network. In non-blocking mode, this function always returns immediately; to force the data to be written, call flush().
Reimplemented from QIODevice.
See also putch(), read(), and setBlocking().
Copyright © 2004 Trolltech. | Trademarks | Qt 4.0.0-tp2 |