com.trolltech.qt.network
Class QAbstractSocket

java.lang.Object
  extended by com.trolltech.qt.internal.QSignalEmitterInternal
      extended by com.trolltech.qt.QSignalEmitter
          extended by com.trolltech.qt.QtJambiObject
              extended by com.trolltech.qt.core.QObject
                  extended by com.trolltech.qt.core.QIODevice
                      extended by com.trolltech.qt.network.QAbstractSocket
All Implemented Interfaces:
QtJambiInterface
Direct Known Subclasses:
QTcpSocket, QUdpSocket

public class QAbstractSocket
extends QIODevice

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 (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.

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::ClosedState, 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;
        byte buffer[] = new byte[50];

        while (true) {
            numRead  = socket.read(buffer);

            // do whatever with array

            numReadTotal += numRead;
            if (numRead == 0 && !socket.waitForReadyRead(1000))
                break;
        }
    
If waitForReadyRead() 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 the network/fortuneclient and network/blockingfortuneclient examples for an overview of both approaches.

QAbstractSocket can be used with QTextStream and QDataStream'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 also:
QFtp, QHttp, and QTcpServer.


Nested Class Summary
static class QAbstractSocket.NetworkLayerProtocol
          This enum describes the network layer protocol values used in Qt.
static class QAbstractSocket.SocketError
          This enum describes the socket errors that can occur.
static class QAbstractSocket.SocketState
          This enum describes the different states in which a socket can be.
static class QAbstractSocket.SocketType
          This enum describes the transport layer protocol.
 
Nested classes/interfaces inherited from class com.trolltech.qt.core.QIODevice
QIODevice.OpenMode, QIODevice.OpenModeFlag
 
Nested classes/interfaces inherited from class com.trolltech.qt.QSignalEmitter
QSignalEmitter.AbstractSignal, QSignalEmitter.PrivateSignal0, QSignalEmitter.PrivateSignal1, QSignalEmitter.PrivateSignal2, QSignalEmitter.PrivateSignal3, QSignalEmitter.PrivateSignal4, QSignalEmitter.PrivateSignal5, QSignalEmitter.PrivateSignal6, QSignalEmitter.PrivateSignal7, QSignalEmitter.PrivateSignal8, QSignalEmitter.PrivateSignal9, QSignalEmitter.Signal0, QSignalEmitter.Signal1, QSignalEmitter.Signal2, QSignalEmitter.Signal3, QSignalEmitter.Signal4, QSignalEmitter.Signal5, QSignalEmitter.Signal6, QSignalEmitter.Signal7, QSignalEmitter.Signal8, QSignalEmitter.Signal9
 
Nested classes/interfaces inherited from class com.trolltech.qt.internal.QSignalEmitterInternal
com.trolltech.qt.internal.QSignalEmitterInternal.AbstractSignalInternal
 
Field Summary
 QSignalEmitter.Signal0 connected
          This signal is emitted after connectToHost() has been called and a connection has been successfully established.
 QSignalEmitter.Signal0 disconnected
          This signal is emitted when the socket has been disconnected.
 QSignalEmitter.Signal1 error
          This signal takes 1 generic argument(s).
 QSignalEmitter.Signal0 hostFound
          This signal is emitted after connectToHost() has been called and the host lookup has succeeded.
 QSignalEmitter.Signal2 proxyAuthenticationRequired
          This signal takes 2 generic argument(s).
 QSignalEmitter.Signal1 stateChanged
          This signal takes 1 generic argument(s).
 
Fields inherited from class com.trolltech.qt.core.QIODevice
aboutToClose, bytesWritten, readChannelFinished, readyRead
 
Fields inherited from class com.trolltech.qt.internal.QSignalEmitterInternal
currentSender
 
Constructor Summary
QAbstractSocket(QAbstractSocket.SocketType socketType, QObject parent)
          Creates a new abstract socket of type socketType.
 
Method Summary
 void abort()
          Aborts the current connection and resets the socket.
 void connectToHost(QHostAddress host, int port)
          Attempts to make a connection to address on port port.
 void connectToHost(QHostAddress host, int port, QIODevice.OpenMode mode)
          Attempts to make a connection to address on port port.
 void connectToHost(QHostAddress host, int port, QIODevice.OpenModeFlag[] mode)
          Attempts to make a connection to address on port port.
 void connectToHost(java.lang.String host, int port)
          Attempts to make a connection to hostName on the given port.
 void connectToHost(java.lang.String host, int port, QIODevice.OpenMode mode)
          Attempts to make a connection to hostName on the given port.
 void connectToHost(java.lang.String host, int port, QIODevice.OpenModeFlag[] mode)
          Attempts to make a connection to hostName on the given port.
 void disconnectFromHost()
          Attempts to close the socket.
protected  void disconnectFromHostImplementation()
          Contains the implementation of disconnectFromHost().
 QAbstractSocket.SocketError error()
          Returns the type of error that last occurred.
 boolean flush()
          This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking.
 boolean isValid()
          Returns true if the socket is valid and ready for use; otherwise returns false.
 QHostAddress localAddress()
          Returns the host address of the local socket if available; otherwise returns QHostAddress::Null .
 int localPort()
          Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.
 QHostAddress peerAddress()
          Returns the address of the connected peer if the socket is in ConnectedState ; otherwise returns QHostAddress::Null .
 java.lang.String peerName()
          Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called.
 int peerPort()
          Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0.
 QNetworkProxy proxy()
          Returns the network proxy for this socket.
 long readBufferSize()
          Returns the size of the internal read buffer.
protected  void setLocalAddress(QHostAddress address)
          Sets the address on the local side of a connection to address.
protected  void setLocalPort(int port)
          Sets the local port of this QAbstractSocket to port.
protected  void setPeerAddress(QHostAddress address)
          Sets the address of the remote side of the connection to address.
protected  void setPeerName(java.lang.String name)
          Sets the host name of the remote peer to name.
protected  void setPeerPort(int port)
          Sets the peer port of this QAbstractSocket to port.
 void setProxy(QNetworkProxy networkProxy)
          Sets the explicit network proxy for this socket to networkProxy.
 void setReadBufferSize(long size)
          Sets the size of QAbstractSocket's internal read buffer to be size bytes.
 boolean setSocketDescriptor(int socketDescriptor)
          Initializes QAbstractSocket with the native socket descriptor socketDescriptor.
 boolean setSocketDescriptor(int socketDescriptor, QAbstractSocket.SocketState state)
          Initializes QAbstractSocket with the native socket descriptor socketDescriptor.
 boolean setSocketDescriptor(int socketDescriptor, QAbstractSocket.SocketState state, QIODevice.OpenMode openMode)
          Initializes QAbstractSocket with the native socket descriptor socketDescriptor.
 boolean setSocketDescriptor(int socketDescriptor, QAbstractSocket.SocketState state, QIODevice.OpenModeFlag[] openMode)
           
protected  void setSocketError(QAbstractSocket.SocketError socketError)
          Sets the type of error that last occurred to socketError.
protected  void setSocketState(QAbstractSocket.SocketState state)
          Sets the state of the socket to state.
 int socketDescriptor()
          Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise returns -1.
 QAbstractSocket.SocketType socketType()
          Returns the socket type (TCP, UDP, or other).
 QAbstractSocket.SocketState state()
          Returns the state of the socket.
 boolean waitForConnected()
          Waits until the socket is connected, up to msecs milliseconds.
 boolean waitForConnected(int msecs)
          Waits until the socket is connected, up to msecs milliseconds.
 boolean waitForDisconnected()
          Waits until the socket has disconnected, up to msecs milliseconds.
 boolean waitForDisconnected(int msecs)
          Waits until the socket has disconnected, up to msecs milliseconds.
 
Methods inherited from class com.trolltech.qt.core.QIODevice
atEnd, bytesAvailable, bytesToWrite, canReadLine, close, errorString, getByte, isOpen, isReadable, isSequential, isTextModeEnabled, isWritable, open, open, openMode, peek, peek, pos, putByte, read, read, readAll, readData, readLine, readLine, readLine, readLineData, reset, seek, setErrorString, setOpenMode, setOpenMode, setTextModeEnabled, size, ungetByte, waitForBytesWritten, waitForReadyRead, write, write, writeData
 
Methods inherited from class com.trolltech.qt.core.QObject
childEvent, children, connectSlotsByName, customEvent, disposeLater, dumpObjectInfo, dumpObjectTree, dynamicPropertyNames, event, eventFilter, findChild, findChild, findChild, findChildren, findChildren, findChildren, findChildren, indexOfProperty, installEventFilter, isWidgetType, killTimer, moveToThread, objectName, parent, properties, property, removeEventFilter, setObjectName, setParent, setProperty, startTimer, timerEvent, toString, userProperty
 
Methods inherited from class com.trolltech.qt.QtJambiObject
dispose, disposed, equals, finalize, reassignNativeResources, tr, tr, tr
 
Methods inherited from class com.trolltech.qt.QSignalEmitter
blockSignals, disconnect, disconnect, signalsBlocked, signalSender, thread
 
Methods inherited from class com.trolltech.qt.internal.QSignalEmitterInternal
__qt_signalInitialization
 
Methods inherited from class java.lang.Object
clone, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface com.trolltech.qt.QtJambiInterface
disableGarbageCollection, nativeId, nativePointer, reenableGarbageCollection, setJavaOwnership
 

Field Detail

connected

public final QSignalEmitter.Signal0 connected
This signal is emitted after connectToHost() has been called and a connection has been successfully established.

See also:
connectToHost(), and disconnected() .


disconnected

public final QSignalEmitter.Signal0 disconnected
This signal is emitted when the socket has been disconnected.

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

See also:
connectToHost(), disconnectFromHost(), and abort().


error

public final QSignalEmitter.Signal1 error

This signal takes 1 generic argument(s). We list their type and the name they go by in the description of this signal. <com.trolltech.qt.network.QAbstractSocket$SocketError(named: socketError)>:

This signal is emitted after an error occurred. The socketError 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 with Q_REGISTER_METATYPE.

See also:
error(), and errorString().


hostFound

public final QSignalEmitter.Signal0 hostFound
This signal is emitted after connectToHost() has been called and the host lookup has succeeded.

See also:
connected() .


stateChanged

public final QSignalEmitter.Signal1 stateChanged

This signal takes 1 generic argument(s). We list their type and the name they go by in the description of this signal. <com.trolltech.qt.network.QAbstractSocket$SocketState(named: socketState)>:

This signal is emitted whenever QAbstractSocket's state changes. The socketState 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.

See also:
state().


proxyAuthenticationRequired

public QSignalEmitter.Signal2 proxyAuthenticationRequired

This signal takes 2 generic argument(s). We list their type and the name they go by in the description of this signal. <com.trolltech.qt.network.QNetworkProxy(named: proxy), com.trolltech.qt.network.QAuthenticator(named: authenticator)>:

This signal can be emitted when a proxy that requires authentication is used. The authenticator 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.

See also:
QAuthenticator, and QNetworkProxy.

Constructor Detail

QAbstractSocket

public QAbstractSocket(QAbstractSocket.SocketType socketType,
                       QObject parent)
Creates a new abstract socket of type socketType. The parent argument is passed to QObject's constructor.

See also:
socketType(), QTcpSocket, and QUdpSocket.

Method Detail

abort

public void abort()
Aborts the current connection and resets the socket. Unlike disconnectFromHost(), this function immediately closes the socket, discarding any pending data in the write buffer.

See also:
disconnectFromHost(), and close().


disconnectFromHost

public final void disconnectFromHost()
Attempts to close the socket. If there is pending data waiting to be written, QAbstractSocket will enter ClosingState and wait until all data has been written. Eventually, it will enter UnconnectedState and emit the disconnected() signal.

See also:
connectToHost().


disconnectFromHostImplementation

protected void disconnectFromHostImplementation()
Contains the implementation of disconnectFromHost().


error

public final QAbstractSocket.SocketError error()
Returns the type of error that last occurred.

See also:
state(), and errorString().


flush

public boolean 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 need QAbstractSocket 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, because QAbstractSocket will start sending data automatically once control goes back to the event loop. In the absence of an event loop, call waitForBytesWritten() instead.

See also:
write(), and waitForBytesWritten().


isValid

public final boolean isValid()
Returns true if the socket is valid and ready for use; otherwise returns false.

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

See also:
state().


localAddress

public final QHostAddress localAddress()
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(), peerAddress(), and setLocalAddress().


peerAddress

public final QHostAddress peerAddress()
Returns the address of the connected peer if the socket is in ConnectedState ; otherwise returns QHostAddress::Null .

See also:
peerName(), peerPort(), localAddress(), and setPeerAddress().


peerName

public final java.lang.String peerName()
Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called.

See also:
peerAddress(), peerPort(), and setPeerName().


proxy

public final QNetworkProxy proxy()
Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used, which means this socket will query the default proxy settings for the application.

See also:
setProxy(), QNetworkProxy, and QNetworkProxyFactory.


readBufferSize

public final long readBufferSize()
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().


setLocalAddress

protected final void setLocalAddress(QHostAddress address)
Sets the address on the local side of a connection to address.

You can call this function in a subclass of QAbstractSocket to change the return value of the localAddress() 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()).

See also:
localAddress(), setLocalPort(), and setPeerAddress().


setPeerAddress

protected final void setPeerAddress(QHostAddress address)
Sets the address of the remote side of the connection to address.

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

See also:
peerAddress(), setPeerPort(), and setLocalAddress().


setPeerName

protected final void setPeerName(java.lang.String name)
Sets the host name of the remote peer to name.

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

See also:
peerName().


setProxy

public final void setProxy(QNetworkProxy networkProxy)
Sets the explicit network proxy for this socket to networkProxy.

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

The following code example is written in c++.

socket->setProxy(QNetworkProxy::NoProxy);
The default value for the proxy is QNetworkProxy::DefaultProxy , which means the socket will use the application settings: if a proxy is set with QNetworkProxy::setApplicationProxy, it will use that; otherwise, if a factory is set with QNetworkProxyFactory::setApplicationProxyFactory, it will query that factory with type QNetworkProxyQuery::TcpSocket .

See also:
proxy(), QNetworkProxy, and QNetworkProxyFactory::queryProxy().


setReadBufferSize

public void setReadBufferSize(long size)
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.

Only QTcpSocket uses QAbstractSocket'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 on QUdpSocket has no effect.

See also:
readBufferSize(), and read().


setSocketDescriptor

public final boolean setSocketDescriptor(int socketDescriptor,
                                         QAbstractSocket.SocketState state,
                                         QIODevice.OpenModeFlag[] openMode)

setSocketDescriptor

public final boolean setSocketDescriptor(int socketDescriptor,
                                         QAbstractSocket.SocketState state)
Initializes QAbstractSocket with the native socket descriptor socketDescriptor. Returns true if socketDescriptor is accepted as a valid socket descriptor; otherwise returns false. The socket is opened in the mode specified by openMode, and enters the socket state specified by socketState.

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

See also:
socketDescriptor().


setSocketDescriptor

public final boolean setSocketDescriptor(int socketDescriptor)
Initializes QAbstractSocket with the native socket descriptor socketDescriptor. Returns true if socketDescriptor is accepted as a valid socket descriptor; otherwise returns false. The socket is opened in the mode specified by openMode, and enters the socket state specified by socketState.

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

See also:
socketDescriptor().


setSocketDescriptor

public boolean setSocketDescriptor(int socketDescriptor,
                                   QAbstractSocket.SocketState state,
                                   QIODevice.OpenMode openMode)
Initializes QAbstractSocket with the native socket descriptor socketDescriptor. Returns true if socketDescriptor is accepted as a valid socket descriptor; otherwise returns false. The socket is opened in the mode specified by openMode, and enters the socket state specified by socketState.

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

See also:
socketDescriptor().


setSocketError

protected final void setSocketError(QAbstractSocket.SocketError socketError)
Sets the type of error that last occurred to socketError.

See also:
setSocketState(), and setErrorString().


setSocketState

protected final void setSocketState(QAbstractSocket.SocketState state)
Sets the state of the socket to state.

See also:
state().


socketDescriptor

public final int socketDescriptor()
Returns the native socket descriptor of the QAbstractSocket object if this is available; otherwise returns -1.

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

The socket descriptor is not available when QAbstractSocket is in UnconnectedState .

See also:
setSocketDescriptor().


socketType

public final QAbstractSocket.SocketType socketType()
Returns the socket type (TCP, UDP, or other).

See also:
QTcpSocket, and QUdpSocket.


state

public final QAbstractSocket.SocketState state()
Returns the state of the socket.

See also:
error().


waitForConnected

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

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

The following code example is written in c++.

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 than msecs, depending on the time it takes to complete the host lookup.

See also:
connectToHost(), and connected() .


waitForConnected

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

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

The following code example is written in c++.

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 than msecs, depending on the time it takes to complete the host lookup.

See also:
connectToHost(), and connected() .


waitForDisconnected

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

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

The following code example is written in c++.

socket->disconnectFromHost();
    if (socket->state() == QAbstractSocket::UnconnectedState || 
        socket->waitForDisconnected(1000))
        qDebug("Disconnected!");
If msecs is -1, this function will not time out.

See also:
disconnectFromHost(), and close().


waitForDisconnected

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

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

The following code example is written in c++.

socket->disconnectFromHost();
    if (socket->state() == QAbstractSocket::UnconnectedState || 
        socket->waitForDisconnected(1000))
        qDebug("Disconnected!");
If msecs is -1, this function will not time out.

See also:
disconnectFromHost(), and close().


connectToHost

public final void connectToHost(java.lang.String host,
                                int port,
                                QIODevice.OpenMode mode)
Attempts to make a connection to hostName on the given port.

The socket is opened in the given openMode and first enters HostLookupState , then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters ConnectingState . It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters 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:
state(), peerName(), peerAddress(), peerPort(), and waitForConnected().


connectToHost

public final void connectToHost(java.lang.String host,
                                int port,
                                QIODevice.OpenModeFlag[] mode)
Attempts to make a connection to hostName on the given port.

The socket is opened in the given openMode and first enters HostLookupState , then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters ConnectingState . It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters 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:
state(), peerName(), peerAddress(), peerPort(), and waitForConnected().


connectToHost

public final void connectToHost(java.lang.String host,
                                int port)
Attempts to make a connection to hostName on the given port.

The socket is opened in the given openMode and first enters HostLookupState , then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters ConnectingState . It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters 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:
state(), peerName(), peerAddress(), peerPort(), and waitForConnected().


connectToHost

public final void connectToHost(QHostAddress host,
                                int port,
                                QIODevice.OpenMode mode)
Attempts to make a connection to address on port port.


connectToHost

public final void connectToHost(QHostAddress host,
                                int port,
                                QIODevice.OpenModeFlag[] mode)
Attempts to make a connection to address on port port.


connectToHost

public final void connectToHost(QHostAddress host,
                                int port)
Attempts to make a connection to address on port port.


localPort

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


peerPort

public final int peerPort()
Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0.


setLocalPort

protected final void setLocalPort(int port)
Sets the local port of this QAbstractSocket to port.


setPeerPort

protected final void setPeerPort(int port)
Sets the peer port of this QAbstractSocket to port.