
We bake cookies in your browser for a better experience. Using this site means that you consent.Read More
TheQ3Socket class provides a buffered TCP connection.More...
| Header: | #include <Q3Socket> |
| Inherits: | QIODevice |
| enum | Error { ErrConnectionRefused, ErrHostNotFound, ErrSocketRead } |
| enum | State { Idle, HostLookup, Connecting, Connected, Closing } |
| Q3Socket(QObject * parent = 0, const char * name = 0) | |
| virtual | ~Q3Socket() |
| QHostAddress | address() const |
| Offset | at() const |
| bool | at(Offset index) |
| void | clearPendingData() |
| virtual void | connectToHost(const QString & host, Q_UINT16 port) |
| bool | flush() |
| int | getch() |
| bool | open(int m) |
| QHostAddress | peerAddress() const |
| QString | peerName() const |
| Q_UINT16 | peerPort() const |
| Q_UINT16 | port() const |
| int | putch(int ch) |
| Q_ULONG | readBufferSize() const |
| void | setReadBufferSize(Q_ULONG bufSize) |
| virtual void | setSocket(int socket) |
| virtual void | setSocketDevice(Q3SocketDevice * device) |
| int | socket() const |
| Q3SocketDevice * | socketDevice() |
| State | state() const |
| int | ungetch(int ch) |
| Q_ULONG | waitForMore(int msecs, bool * timeout) const |
| Q_ULONG | waitForMore(int msecs) const |
| virtual bool | atEnd() const |
| virtual qint64 | bytesAvailable() const |
| virtual qint64 | bytesToWrite() const |
| virtual bool | canReadLine() const |
| virtual void | close() |
| virtual bool | open(OpenMode m) |
| virtual Offset | size() const |
| void | bytesWritten(int nbytes) |
| void | connected() |
| void | connectionClosed() |
| void | delayedCloseFinished() |
| void | error(int error) |
| void | hostFound() |
| void | readyRead() |
| virtual qint64 | readData(char * data, qint64 maxlen) |
| virtual qint64 | writeData(const char * data, qint64 len) |
TheQ3Socket class provides a buffered TCP connection.
It provides a totally non-blockingQIODevice, and modifies and extends the API ofQIODevice with socket-specific code.
The functions you're likely to call most areconnectToHost(),bytesAvailable(),canReadLine() and the ones it inherits fromQIODevice.
connectToHost() is the most-used function. As its name implies, it opens a connection to a named host.
Most network protocols are either packet-oriented or line-oriented.canReadLine() indicates whether a connection contains an entire unread line or not, andbytesAvailable() returns the number of bytes available for reading.
The signalserror(),connected(),readyRead() andconnectionClosed() inform you of the progress of the connection. There are also some less commonly used signals.hostFound() is emitted whenconnectToHost() has finished its DNS lookup and is starting its TCP connection.delayedCloseFinished() is emitted whenclose() succeeds.bytesWritten() is emitted whenQ3Socket moves data from its "to be written" queue into the TCP implementation.
There are several access functions for the socket:state() returns whether the object is idle, is doing a DNS lookup, is connecting, has an operational connection, etc.address() andport() return the IP address and port used for the connection. ThepeerAddress() andpeerPort() functions return the IP address and port used by the peer, andpeerName() returns the name of the peer (normally the name that was passed toconnectToHost()).socketDevice() returns a pointer to theQ3SocketDevice used for this socket.
Q3Socket inheritsQIODevice, and reimplements some functions. In general, you can treat it as aQIODevice for writing, and mostly also for reading. The match isn't perfect, since theQIODevice API is designed for devices that are controlled by the same machine, and an asynchronous peer-to-peer network connection isn't quite like that. For example, there is nothing that matchesQIODevice::size() exactly. The documentation foropen(),close(),flush(),size(),at(),atEnd(),readBlock(),writeBlock(),getch(),putch(),ungetch() andreadLine() describes the differences in detail.
Warning:Q3Socket is not suitable for use in threads. If you need to uses sockets in threads use the lower-levelQ3SocketDevice class.
See alsoQ3SocketDevice,QHostAddress, andQSocketNotifier.
This enum specifies the possible errors:
| Constant | Value | Description |
|---|---|---|
Q3Socket::ErrConnectionRefused | 0 | if the connection was refused |
Q3Socket::ErrHostNotFound | 1 | if the host was not found |
Q3Socket::ErrSocketRead | 2 | if a read from the socket failed |
This enum defines the connection states:
| Constant | Value | Description |
|---|---|---|
Q3Socket::Idle | 0 | if there is no connection |
Q3Socket::HostLookup | 1 | during a DNS lookup |
Q3Socket::Connecting | 2 | during TCP connection establishment |
Q3Socket::Connected | 3 | when there is an operational connection |
Q3Socket::Closing | 4 | if the socket is closing down, but is not yet closed. |
Creates aQ3Socket object inQ3Socket::Idle state.
Theparent andname arguments are passed on to theQObject constructor.
[virtual]Q3Socket::~Q3Socket()Destroys the socket. Closes the connection if necessary.
See alsoclose().
Returns the host address of this socket. (This is normally the main IP address of the host, but can be e.g. 127.0.0.1 for connections to localhost.)
Returns the current read index. SinceQ3Socket is a sequential device, the current read index is always zero.
This is an overloaded function.
Moves the read index forward toindex and returns true if the operation was successful; otherwise returns false. Moving the index forward means skipping incoming data.
[virtual]bool Q3Socket::atEnd() constReimplemented fromQIODevice::atEnd().
Returns true if there is no more data to read; otherwise returns false.
[virtual]qint64 Q3Socket::bytesAvailable() constReimplemented fromQIODevice::bytesAvailable().
Returns the number of incoming bytes that can be read, i.e. the size of the input buffer. Equivalent tosize().
See alsobytesToWrite().
[virtual]qint64 Q3Socket::bytesToWrite() constReimplemented fromQIODevice::bytesToWrite().
Returns the number of bytes that are waiting to be written, i.e. the size of the output buffer.
See alsobytesAvailable() andclearPendingData().
[signal]void Q3Socket::bytesWritten(int nbytes)This signal is emitted when data has been written to the network. Thenbytes parameter specifies how many bytes were written.
ThebytesToWrite() function is often used in the same context; it indicates how many buffered bytes there are left to write.
See alsowriteBlock() andbytesToWrite().
[virtual]bool Q3Socket::canReadLine() constReimplemented fromQIODevice::canReadLine().
Returns true if it's possible to read an entire line of text from this socket at this time; otherwise returns false.
Note that if the peer closes the connection unexpectedly, this function returns false. This means that loops such as this won't work:
while(!socket->canReadLine() )// WRONG ;
See alsoreadLine().
Deletes the data that is waiting to be written. This is useful if you want to close the socket without waiting for all the data to be written.
See alsobytesToWrite(),close(), anddelayedCloseFinished().
[virtual]void Q3Socket::close()Reimplemented fromQIODevice::close().
Closes the socket.
The read buffer is cleared.
If the output buffer is empty, the state is set toQ3Socket::Idle and the connection is terminated immediately. If the output buffer still contains data to be written,Q3Socket goes into theQ3Socket::Closing state and the rest of the data will be written. When all of the outgoing data have been written, the state is set toQ3Socket::Idle and the connection is terminated. At this point, thedelayedCloseFinished() signal is emitted.
If you don't want that the data of the output buffer is written, callclearPendingData() before you call close().
See alsostate(),bytesToWrite(), andclearPendingData().
[virtual]void Q3Socket::connectToHost(constQString & host,Q_UINT16 port)Attempts to make a connection tohost on the specifiedport and return immediately.
Any connection or pending connection is closed immediately, andQ3Socket goes into theHostLookup state. When the lookup succeeds, it emitshostFound(), starts a TCP connection and goes into theConnecting state. Finally, when the connection succeeds, it emitsconnected() and goes into theConnected state. If there is an error at any point, it emitserror().
host may be an IP address in string form, or it may be a DNS name.Q3Socket will do a normal DNS lookup if required. Note thatport is in native byte order, unlike some other libraries.
See alsostate().
[signal]void Q3Socket::connected()This signal is emitted afterconnectToHost() has been called and a connection has been successfully established.
See alsoconnectToHost() andconnectionClosed().
[signal]void Q3Socket::connectionClosed()This signal is emitted when the other end has closed the connection. The read buffers may contain buffered input data which you can read after the connection was closed.
See alsoconnectToHost() andclose().
[signal]void Q3Socket::delayedCloseFinished()This signal is emitted when a delayed close is finished.
If you callclose() and there is buffered output data to be written,Q3Socket goes into theQ3Socket::Closing state and returns immediately. It will then keep writing to the socket until all the data has been written. Then, the delayedCloseFinished() signal is emitted.
See alsoclose().
[signal]void Q3Socket::error(int error)This signal is emitted after an error occurred. Theerror parameter is theError value.
Implementation of the abstract virtual QIODevice::flush() function. This function always returns true.
Reads a single byte/character from the internal read buffer. Returns the byte/character read, or -1 if there is nothing to be read.
See alsobytesAvailable() andputch().
[signal]void Q3Socket::hostFound()This signal is emitted afterconnectToHost() has been called and the host lookup has succeeded.
See alsoconnected().
[virtual]bool Q3Socket::open(OpenMode m)Reimplemented fromQIODevice::open().
Opens the socket using the specifiedQIODevice file modem. This function is called automatically when needed and you should not call it yourself.
See alsoclose().
This is an overloaded function.
Returns the address of the connected peer if the socket is in Connected state; otherwise an emptyQHostAddress is returned.
Returns the host name as specified to theconnectToHost() function. An empty string is returned if none has been set.
Returns the peer's host port number, normally as specified to theconnectToHost() function. If none has been set, this function returns 0.
Note that Qt always uses native byte order, i.e. 67 is 67 in Qt; there is no need to call htons().
Returns the host port number of this socket, in native byte order.
Writes the characterch to the output buffer.
Returnsch, or -1 if an error occurred.
See alsogetch().
Returns the size of the read buffer.
See alsosetReadBufferSize().
[virtual protected]qint64 Q3Socket::readData(char * data,qint64 maxlen)Reimplemented fromQIODevice::readData().
Readsmaxlen bytes from the socket intodata and returns the number of bytes read. Returns -1 if an error occurred.
[signal]void Q3Socket::readyRead()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 all the data, this class buffers the data and you can read it later, but no signal is emitted unless new data arrives. A good practice is to read all data in the slot connected to this signal unless you are sure that you need to receive more data to be able to process it.
See alsoreadBlock(),readLine(), andbytesAvailable().
Sets the size of theQ3Socket's internal read buffer tobufSize.
UsuallyQ3Socket reads all data that is available from the operating system's socket. If the buffer size is limited to a certain size, this means that theQ3Socket class doesn't buffer more than this size of data.
If the size of the read buffer is 0, the read buffer is unlimited and all incoming data is buffered. This is the default.
If you read the data in thereadyRead() signal, you shouldn't use this option since it might slow down your program unnecessary. This option is useful if you only need to read the data at certain points in time, like in a realtime streaming application.
See alsoreadBufferSize().
[virtual]void Q3Socket::setSocket(int socket)Sets the socket to usesocket and thestate() toConnected. The socket must already be connected.
This allows us to use theQ3Socket class as a wrapper for other socket types (e.g. Unix Domain Sockets).
See alsosocket().
[virtual]void Q3Socket::setSocketDevice(Q3SocketDevice * device)Sets the internal socket device todevice. Passing adevice of 0 will cause the internal socket device to be used. Any existing connection will be disconnected before using the newdevice.
The new device should not be connected before being associated with aQ3Socket; after setting the socket callconnectToHost() to make the connection.
This function is useful if you need to subclassQ3SocketDevice and want to use theQ3Socket API, for example, to implement Unix domain sockets.
See alsosocketDevice().
[virtual]Offset Q3Socket::size() constReimplemented fromQIODevice::size().
Returns the number of incoming bytes that can be read right now (likebytesAvailable()).
Returns the socket number, or -1 if there is no socket at the moment.
See alsosetSocket().
Returns a pointer to the internal socket device.
There is normally no need to manipulate the socket device directly since this class does the necessary setup for most applications.
See alsosetSocketDevice().
Returns the current state of the socket connection.
See alsoQ3Socket::State.
This implementation of the virtual functionQIODevice::ungetch() prepends the characterch to the read buffer so that the next read returns this character as the first character of the output.
Wait up tomsecs milliseconds for more data to be available.
Ifmsecs is -1 the call will block indefinitely.
Returns the number of bytes available.
Iftimeout is non-null and no error occurred (i.e. it does not return -1): this function sets *timeout to true, if the reason for returning was that the timeout was reached; otherwise it sets *timeout to false. This is useful to find out if the peer closed the connection.
Warning: This is a blocking call and should be avoided in event driven applications.
See alsobytesAvailable().
This is an overloaded function.
[virtual protected]qint64 Q3Socket::writeData(constchar * data,qint64 len)Reimplemented fromQIODevice::writeData().
Writeslen bytes to the socket fromdata and returns the number of bytes written. Returns -1 if an error occurred.
© 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.