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:
- Instantiate PySide.QtNetwork.QTcpSocket or PySide.QtNetwork.QUdpSocket .
- Create a native socket descriptor, instantiate PySide.QtNetwork.QAbstractSocket , and call PySide.QtNetwork.QAbstractSocket.setSocketDescriptor() to wrap the native socket.
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:
- PySide.QtNetwork.QAbstractSocket.waitForConnected() blocks until a connection has been established.
- PySide.QtNetwork.QAbstractSocket.waitForReadyRead() blocks until new data is available for reading.
- PySide.QtNetwork.QAbstractSocket.waitForBytesWritten() blocks until one payload of data has been written to the socket.
- PySide.QtNetwork.QAbstractSocket.waitForDisconnected() blocks until the connection has closed.
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.
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>>().
Creates a new abstract socket of type socketType . The parent argument is passed to PySide.QtCore.QObject ‘s constructor.
This enum describes the transport layer protocol.
|QAbstractSocket.UnknownSocketType||Other than TCP and UDP|
This enum describes the socket errors that can occur.
|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 ) (This value was introduced in 4.4.)|
|QAbstractSocket.UnfinishedSocketOperationError||Used 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.ProxyConnectionRefusedError||Could not contact the proxy server because the connection to that server was denied (This value was introduced in 4.5.)|
|QAbstractSocket.ProxyConnectionClosedError||The 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.ProxyConnectionTimeoutError||The 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.ProxyNotFoundError||The proxy address set with PySide.QtNetwork.QAbstractSocket.setProxy() (or the application proxy) was not found. (This value was introduced in 4.5.)|
|QAbstractSocket.ProxyProtocolError||The 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||An unidentified error occurred.|
This enum describes the network layer protocol values used in Qt.
|QAbstractSocket.UnknownNetworkLayerProtocol||Other than IPv4 and IPv6|
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 .
|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|
|QAbstractSocket.MulticastTtlOption||Set this to an integer value to set IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.|
|QAbstractSocket.MulticastLoopbackOption||Set this to 1 to enable the IP_MULTICAST_LOOP (multicast loopback) socket option.|
This enum was introduced or modified in Qt 4.6
This enum describes the different states in which a socket can be.
|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.|
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.
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.
Contains the implementation of PySide.QtNetwork.QAbstractSocket.disconnectFromHost() .
Returns the type of error that last occurred.
|Parameters:||arg__1 – PySide.QtNetwork.QAbstractSocket.SocketError|
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.
Returns true if the socket is valid and ready for use; otherwise returns false.
The socket’s state must be ConnectedState before reading and writing can occur.
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.
Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.
Returns the address of the connected peer if the socket is in ConnectedState ; otherwise returns QHostAddress.Null .
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.
Returns the port of the connected peer if the socket is in ConnectedState ; otherwise returns 0.
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.
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.
|Parameters:||address – PySide.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() ).
|Parameters:||port – PySide.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() ).
|Parameters:||address – PySide.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.
|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.
|Parameters:||port – PySide.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.
|Parameters:||networkProxy – PySide.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:
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 .
|Parameters:||size – PySide.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.
|Parameters:||socketError – PySide.QtNetwork.QAbstractSocket.SocketError|
Sets the type of error that last occurred to socketError .
|Parameters:||state – PySide.QtNetwork.QAbstractSocket.SocketState|
Sets the state of the socket to state .
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 .
|Parameters:||option – PySide.QtNetwork.QAbstractSocket.SocketOption|
Returns the socket type (TCP, UDP, or other).
Returns the state of the socket.
|Parameters:||arg__1 – PySide.QtNetwork.QAbstractSocket.SocketState|
|Parameters:||msecs – PySide.QtCore.int|
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.
This function may wait slightly longer than msecs , depending on the time it takes to complete the host lookup.
Multiple calls to this functions do not accumulate the time. If the function times out, the connecting process will be aborted.
|Parameters:||msecs – PySide.QtCore.int|
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.