Table Of Contents

Previous topic

QLocalSocket

Next topic

QNetworkReply

QAbstractSocket

Inheritance diagram of QAbstractSocket

Inherited by: QUdpSocket, QTcpSocket, QSslSocket

Synopsis

Functions

Slots

Signals

Detailed Description

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

PySide.QtNetwork.QAbstractSocket is the base class for PySide.QtNetwork.QTcpSocket and PySide.QtNetwork.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.

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

At any time, PySide.QtNetwork.QAbstractSocket has a state (returned by PySide.QtNetwork.QAbstractSocket.state() ). The initial state is UnconnectedState . After calling PySide.QtNetwork.QAbstractSocket.connectToHost() , the socket first enters HostLookupState . If the host is found, PySide.QtNetwork.QAbstractSocket enters ConnectingState and emits the PySide.QtNetwork.QAbstractSocket.hostFound() signal. When the connection has been established, it enters ConnectedState and emits PySide.QtNetwork.QAbstractSocket.connected() . If an error occurs at any stage, PySide.QtNetwork.QAbstractSocket.error() is emitted. Whenever the state changes, PySide.QtNetwork.QAbstractSocket.stateChanged() is emitted. For convenience, PySide.QtNetwork.QAbstractSocket.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 PySide.QtCore.QIODevice.read() or PySide.QtCore.QIODevice.write() , or use the convenience functions PySide.QtCore.QIODevice.readLine() and PySide.QtCore.QIODevice.readAll() . PySide.QtNetwork.QAbstractSocket also inherits PySide.QtCore.QIODevice.getChar() , PySide.QtCore.QIODevice.putChar() , and PySide.QtCore.QIODevice.ungetChar() from PySide.QtCore.QIODevice , which work on single bytes. The PySide.QtCore.QIODevice.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 PySide.QtCore.QIODevice.readyRead() signal is emitted every time a new chunk of data has arrived. PySide.QtNetwork.QAbstractSocket.bytesAvailable() then returns the number of bytes that are available for reading. Typically, you would connect the PySide.QtCore.QIODevice.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 PySide.QtNetwork.QAbstractSocket ‘s internal read buffer. To limit the size of the read buffer, call PySide.QtNetwork.QAbstractSocket.setReadBufferSize() .

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

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

PySide.QtNetwork.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:

numRead = 0
numReadTotal = 0

while(True):
    buffer  = socket.read(50)
    # do whatever with array
    numReadTotal += buffer.size()
    if (buffer.size() == 0 && !socket.waitForReadyRead()):
        break

If PySide.QtCore.QIODevice.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.

Note

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

PySide.QtNetwork.QAbstractSocket can be used with PySide.QtCore.QTextStream and PySide.QtCore.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>>().

class PySide.QtNetwork.QAbstractSocket(socketType, parent)
Parameters:

Creates a new abstract socket of type socketType . The parent argument is passed to PySide.QtCore.QObject ‘s constructor.

PySide.QtNetwork.QAbstractSocket.SocketType

This enum describes the transport layer protocol.

Constant Description
QAbstractSocket.TcpSocket TCP
QAbstractSocket.UdpSocket UDP
QAbstractSocket.UnknownSocketType Other than TCP and UDP
PySide.QtNetwork.QAbstractSocket.SocketError

This enum describes the socket errors that can occur.

Constant Description
QAbstractSocket.ConnectionRefusedError The connection was refused by the peer (or timed out).
QAbstractSocket.RemoteHostClosedError The 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.HostNotFoundError The host address was not found.
QAbstractSocket.SocketAccessError The socket operation failed because the application lacked the required privileges.
QAbstractSocket.SocketResourceError The local system ran out of resources (e.g., too many sockets).
QAbstractSocket.SocketTimeoutError The socket operation timed out.
QAbstractSocket.DatagramTooLargeError The datagram was larger than the operating system’s limit (which can be as low as 8192 bytes).
QAbstractSocket.NetworkError An error occurred with the network (e.g., the network cable was accidentally plugged out).
QAbstractSocket.AddressInUseError The address specified to QUdpSocket.bind() is already in use and was set to be exclusive.
QAbstractSocket.SocketAddressNotAvailableError The address specified to QUdpSocket.bind() does not belong to the host.
QAbstractSocket.UnsupportedSocketOperationError The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support).
QAbstractSocket.ProxyAuthenticationRequiredError The socket is using a proxy, and the proxy requires authentication.
QAbstractSocket.SslHandshakeFailedError The SSL/TLS handshake failed, so the connection was closed (only used in PySide.QtNetwork.QSslSocket )
QAbstractSocket.UnfinishedSocketOperationError Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background).
QAbstractSocket.ProxyConnectionRefusedError Could not contact the proxy server because the connection to that server was denied
QAbstractSocket.ProxyConnectionClosedError The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)
QAbstractSocket.ProxyConnectionTimeoutError The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase.
QAbstractSocket.ProxyNotFoundError The proxy address set with PySide.QtNetwork.QAbstractSocket.setProxy() (or the application proxy) was not found.
QAbstractSocket.ProxyProtocolError The connection negotiation with the proxy server because the response from the proxy server could not be understood.
QAbstractSocket.UnknownSocketError An unidentified error occurred.
PySide.QtNetwork.QAbstractSocket.NetworkLayerProtocol

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

Constant Description
QAbstractSocket.IPv4Protocol IPv4
QAbstractSocket.IPv6Protocol IPv6
QAbstractSocket.UnknownNetworkLayerProtocol Other than IPv4 and IPv6
PySide.QtNetwork.QAbstractSocket.SocketOption

This enum represents the options that can be set on a socket. If desired, they can be set after having received the PySide.QtNetwork.QAbstractSocket.connected() signal from the socket or after having received a new socket from a PySide.QtNetwork.QTcpServer .

Constant Description
QAbstractSocket.LowDelayOption Try to optimize the socket for low latency. For a PySide.QtNetwork.QTcpSocket this would set the TCP_NODELAY option and disable Nagle’s algorithm. Set this to 1 to enable.
QAbstractSocket.KeepAliveOption Set this to 1 to enable the SO_KEEPALIVE socket option

Note

This enum was introduced or modified in Qt 4.6

PySide.QtNetwork.QAbstractSocket.SocketState

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

Constant Description
QAbstractSocket.UnconnectedState The socket is not connected.
QAbstractSocket.HostLookupState The socket is performing a host name lookup.
QAbstractSocket.ConnectingState The socket has started establishing a connection.
QAbstractSocket.ConnectedState A connection is established.
QAbstractSocket.BoundState The socket is bound to an address and port (for servers).
QAbstractSocket.ClosingState The socket is about to close (data may still be waiting to be written).
QAbstractSocket.ListeningState For internal use only.
PySide.QtNetwork.QAbstractSocket.abort()

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

See also

PySide.QtNetwork.QAbstractSocket.disconnectFromHost() PySide.QtNetwork.QAbstractSocket.close()

PySide.QtNetwork.QAbstractSocket.connectToHost(hostName, port[, mode=QIODevice.ReadWrite])
Parameters:
  • hostName – unicode
  • portPySide.QtCore.quint16
  • modePySide.QtCore.QIODevice.OpenMode
PySide.QtNetwork.QAbstractSocket.connectToHost(address, port[, mode=QIODevice.ReadWrite])
Parameters:
PySide.QtNetwork.QAbstractSocket.connectToHostImplementation(hostName, port[, mode=QIODevice.ReadWrite])
Parameters:
  • hostName – unicode
  • portPySide.QtCore.quint16
  • modePySide.QtCore.QIODevice.OpenMode
PySide.QtNetwork.QAbstractSocket.connected()
PySide.QtNetwork.QAbstractSocket.disconnectFromHost()

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

PySide.QtNetwork.QAbstractSocket.disconnectFromHostImplementation()

Contains the implementation of PySide.QtNetwork.QAbstractSocket.disconnectFromHost() .

PySide.QtNetwork.QAbstractSocket.disconnected()
PySide.QtNetwork.QAbstractSocket.error(arg__1)
Parameters:arg__1PySide.QtNetwork.QAbstractSocket.SocketError
PySide.QtNetwork.QAbstractSocket.error()
Return type:PySide.QtNetwork.QAbstractSocket.SocketError

Returns the type of error that last occurred.

See also

PySide.QtNetwork.QAbstractSocket.state() PySide.QtCore.QIODevice.errorString()

PySide.QtNetwork.QAbstractSocket.flush()
Return type:PySide.QtCore.bool

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

See also

PySide.QtCore.QIODevice.write() PySide.QtNetwork.QAbstractSocket.waitForBytesWritten()

PySide.QtNetwork.QAbstractSocket.hostFound()
PySide.QtNetwork.QAbstractSocket.isValid()
Return type:PySide.QtCore.bool

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.

PySide.QtNetwork.QAbstractSocket.localAddress()
Return type:PySide.QtNetwork.QHostAddress

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.

PySide.QtNetwork.QAbstractSocket.localPort()
Return type:PySide.QtCore.quint16

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

PySide.QtNetwork.QAbstractSocket.peerAddress()
Return type:PySide.QtNetwork.QHostAddress

Returns the address of the connected peer if the socket is in ConnectedState ; otherwise returns QHostAddress.Null .

PySide.QtNetwork.QAbstractSocket.peerName()
Return type:unicode

Returns the name of the peer as specified by PySide.QtNetwork.QAbstractSocket.connectToHost() , or an empty PySide.QtCore.QString if PySide.QtNetwork.QAbstractSocket.connectToHost() has not been called.

PySide.QtNetwork.QAbstractSocket.peerPort()
Return type:PySide.QtCore.quint16

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

PySide.QtNetwork.QAbstractSocket.proxy()
Return type:PySide.QtNetwork.QNetworkProxy

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.

PySide.QtNetwork.QAbstractSocket.proxyAuthenticationRequired(proxy, authenticator)
Parameters:
PySide.QtNetwork.QAbstractSocket.readBufferSize()
Return type:PySide.QtCore.qint64

Returns the size of the internal read buffer. This limits the amount of data that the client can receive before you call PySide.QtCore.QIODevice.read() or PySide.QtCore.QIODevice.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

PySide.QtNetwork.QAbstractSocket.setReadBufferSize() PySide.QtCore.QIODevice.read()

PySide.QtNetwork.QAbstractSocket.setLocalAddress(address)
Parameters:addressPySide.QtNetwork.QHostAddress

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

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

PySide.QtNetwork.QAbstractSocket.setLocalPort(port)
Parameters:portPySide.QtCore.quint16

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

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

PySide.QtNetwork.QAbstractSocket.setPeerAddress(address)
Parameters:addressPySide.QtNetwork.QHostAddress

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

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

PySide.QtNetwork.QAbstractSocket.setPeerName(name)
Parameters:name – unicode

Sets the host name of the remote peer to name .

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

PySide.QtNetwork.QAbstractSocket.setPeerPort(port)
Parameters:portPySide.QtCore.quint16

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

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

PySide.QtNetwork.QAbstractSocket.setProxy(networkProxy)
Parameters:networkProxyPySide.QtNetwork.QNetworkProxy

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:

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 .

PySide.QtNetwork.QAbstractSocket.setReadBufferSize(size)
Parameters:sizePySide.QtCore.qint64

Sets the size of PySide.QtNetwork.QAbstractSocket ‘s internal read buffer to be size bytes.

If the buffer size is limited to a certain size, PySide.QtNetwork.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 PySide.QtNetwork.QTcpSocket uses PySide.QtNetwork.QAbstractSocket ‘s internal buffer; PySide.QtNetwork.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 PySide.QtNetwork.QUdpSocket has no effect.

See also

PySide.QtNetwork.QAbstractSocket.readBufferSize() PySide.QtCore.QIODevice.read()

PySide.QtNetwork.QAbstractSocket.setSocketDescriptor(socketDescriptor[, state=ConnectedState[, openMode=QIODevice.ReadWrite]])
Parameters:
Return type:

PySide.QtCore.bool

PySide.QtNetwork.QAbstractSocket.setSocketError(socketError)
Parameters:socketErrorPySide.QtNetwork.QAbstractSocket.SocketError

Sets the type of error that last occurred to socketError .

See also

PySide.QtNetwork.QAbstractSocket.setSocketState() PySide.QtCore.QIODevice.setErrorString()

PySide.QtNetwork.QAbstractSocket.setSocketOption(option, value)
Parameters:
PySide.QtNetwork.QAbstractSocket.setSocketState(state)
Parameters:statePySide.QtNetwork.QAbstractSocket.SocketState

Sets the state of the socket to state .

PySide.QtNetwork.QAbstractSocket.socketDescriptor()
Return type:PySide.QtCore.int

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

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

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

PySide.QtNetwork.QAbstractSocket.socketOption(option)
Parameters:optionPySide.QtNetwork.QAbstractSocket.SocketOption
Return type:object
PySide.QtNetwork.QAbstractSocket.socketType()
Return type:PySide.QtNetwork.QAbstractSocket.SocketType

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

PySide.QtNetwork.QAbstractSocket.state()
Return type:PySide.QtNetwork.QAbstractSocket.SocketState

Returns the state of the socket.

PySide.QtNetwork.QAbstractSocket.stateChanged(arg__1)
Parameters:arg__1PySide.QtNetwork.QAbstractSocket.SocketState
PySide.QtNetwork.QAbstractSocket.waitForConnected([msecs=30000])
Parameters:msecsPySide.QtCore.int
Return type:PySide.QtCore.bool

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 PySide.QtNetwork.QAbstractSocket.error() 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):
    print "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.

Note

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

PySide.QtNetwork.QAbstractSocket.waitForDisconnected([msecs=30000])
Parameters:msecsPySide.QtCore.int
Return type:PySide.QtCore.bool

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 PySide.QtNetwork.QAbstractSocket.error() 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 or \
        socket.waitForDisconnected(1000):
        print "Disconnected!"

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

See also

PySide.QtNetwork.QAbstractSocket.disconnectFromHost() PySide.QtNetwork.QAbstractSocket.close()