Skip to content

PythonQt.Qt.QAbstractSocket

QAbstractSocket

PythonQtInstanceWrapper object

Native bases: PythonQtInstanceWrapper

Supplemental documentation: Qt 5 reference:

Detailed Description

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, errorOccurred() 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. 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::UnconnectedState, 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 errorOccurred(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;
    char buffer[50];

    forever {
        numRead  = socket.read(buffer, 50);

        // do whatever with array

        numReadTotal += numRead;
        if (numRead == 0 && !socket.waitForReadyRead())
            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 fortuneclient and 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.

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

Source: https://doc.qt.io/archives/qt-5.15/qabstractsocket.html

Complete member index

Every captured member retains its own identity. Identical captured declaration text is linked once; this does not establish native inheritance or interchangeable objects.

Member Kind Signature Summary
AddressInUseError attribute Any (shared captured text)
AnyIPProtocol attribute Any (shared captured text)
Append attribute Any (shared captured text)
BindFlag attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
BindMode attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
BoundState attribute Any (shared captured text)
ClosingState attribute Any (shared captured text)
ConnectedState attribute Any (shared captured text)
ConnectingState attribute Any (shared captured text)
ConnectionRefusedError attribute Any (shared captured text)
DatagramTooLargeError attribute Any (shared captured text)
DefaultForPlatform attribute Any (shared captured text)
DontShareAddress attribute Any (shared captured text)
HostLookupState attribute Any (shared captured text)
HostNotFoundError attribute Any (shared captured text)
IPv4Protocol attribute Any (shared captured text)
IPv6Protocol attribute Any (shared captured text)
KeepAliveOption attribute Any (shared captured text)
ListeningState attribute Any (shared captured text)
LowDelayOption attribute Any (shared captured text)
MulticastLoopbackOption attribute Any (shared captured text)
MulticastTtlOption attribute Any (shared captured text)
NetworkError attribute Any (shared captured text)
NetworkLayerProtocol attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
NotOpen attribute Any (shared captured text)
OpenMode attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
OpenModeFlag attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
OperationError attribute Any (shared captured text)
PathMtuSocketOption attribute Any (shared captured text)
PauseMode attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
PauseModes attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
PauseNever attribute Any (shared captured text)
PauseOnSslErrors attribute Any (shared captured text)
ProxyAuthenticationRequiredError attribute Any (shared captured text)
ProxyConnectionClosedError attribute Any (shared captured text)
ProxyConnectionRefusedError attribute Any (shared captured text)
ProxyConnectionTimeoutError attribute Any (shared captured text)
ProxyNotFoundError attribute Any (shared captured text)
ProxyProtocolError attribute Any (shared captured text)
ReadOnly attribute Any (shared captured text)
ReadWrite attribute Any (shared captured text)
ReceiveBufferSizeSocketOption attribute Any (shared captured text)
RemoteHostClosedError attribute Any (shared captured text)
ReuseAddressHint attribute Any (shared captured text)
SctpSocket attribute Any (shared captured text)
SendBufferSizeSocketOption attribute Any (shared captured text)
ShareAddress attribute Any (shared captured text)
SocketAccessError attribute Any (shared captured text)
SocketAddressNotAvailableError attribute Any (shared captured text)
SocketError attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
SocketOption attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
SocketResourceError attribute Any (shared captured text)
SocketState attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
SocketTimeoutError attribute Any (shared captured text)
SocketType attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
SslHandshakeFailedError attribute Any (shared captured text)
SslInternalError attribute Any (shared captured text)
SslInvalidUserDataError attribute Any (shared captured text)
TcpSocket attribute Any (shared captured text)
TemporaryError attribute Any (shared captured text)
Text attribute Any (shared captured text)
Truncate attribute Any (shared captured text)
TypeOfServiceOption attribute Any (shared captured text)
UdpSocket attribute Any (shared captured text)
Unbuffered attribute Any (shared captured text)
UnconnectedState attribute Any (shared captured text)
UnfinishedSocketOperationError attribute Any (shared captured text)
UnknownNetworkLayerProtocol attribute Any (shared captured text)
UnknownSocketError attribute Any (shared captured text)
UnknownSocketType attribute Any (shared captured text)
UnsupportedSocketOperationError attribute Any (shared captured text)
WriteOnly attribute Any (shared captured text)
__init__ function (self, *args: Any, **kwargs: Any) -> None Native constructor; consult class documentation for supported overloads. (shared captured text)
abort function (self) -> None Aborts the current connection and resets the socket. (shared captured text)
aboutToClose function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.aboutToClose; argument details are not documented.
atEnd function (self) -> bool X.atEnd() -> bool (shared captured text)
bind function (self, address: Any, port: int, mode: Any) -> bool X.bind(address, port, mode) -> bool (shared captured text)
blockSignals function (self, b: Any) -> bool X.blockSignals(b) -> bool (shared captured text)
bytesAvailable function (self) -> int X.bytesAvailable() -> int (shared captured text)
bytesToWrite function (self) -> int X.bytesToWrite() -> int (shared captured text)
bytesWritten function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.bytesWritten; argument details are not documented.
canReadLine function (self) -> bool X.canReadLine() -> bool (shared captured text)
channelBytesWritten function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.channelBytesWritten; argument details are not documented.
channelReadyRead function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.channelReadyRead; argument details are not documented.
childEvent function (self, event: Any) -> Any (shared captured text)
children function (self) -> tuple X.children() -> tuple (shared captured text)
className function (self, *args: Any, **kwargs: Any) -> Any Return the classname of the object (shared captured text)
close function (self) -> None Reimplements: [QIODevice::close](https://doc.qt.io/archives/qt-5.15/qiodevice.html#close)(). (shared captured text)
connect function (self, signal: Any, receiver: Any, slot: Any, type: Any) -> bool X.connect(signal, receiver, slot, type) -> bool (shared captured text)
connectToHost function (self, hostName: Any, port: int, mode: Any, protocol: Any) -> None X.connectToHost(hostName, port, mode, protocol) (shared captured text)
connected function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.connected; argument details are not documented.
customEvent function (self, event: Any) -> Any (shared captured text)
delete function (self, *args: Any, **kwargs: Any) -> Any Deletes the C++ object (at your own risk, my friend!) (shared captured text)
deleteLater function (self) -> Any (shared captured text)
destroyed function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.destroyed; argument details are not documented.
disconnect function (self, signal: Any, receiver: Any, slot: Any) -> bool X.disconnect(signal, receiver, slot) -> bool (shared captured text)
disconnectFromHost function (self) -> None Attempts to close the socket. (shared captured text)
disconnected function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.disconnected; argument details are not documented.
dumpObjectInfo function (self) -> Any (shared captured text)
dumpObjectTree function (self) -> Any (shared captured text)
dynamicPropertyNames function (self) -> Any (shared captured text)
error function (self) -> Any Returns the type of error that last occurred. (shared captured text)
errorOccurred function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.errorOccurred; argument details are not documented.
errorString function (self) -> str X.errorString() -> str (shared captured text)
event function (self, event: Any) -> bool X.event(event) -> bool (shared captured text)
eventFilter function (self, watched: Any, event: Any) -> bool X.eventFilter(watched, event) -> bool (shared captured text)
findChild function (self, type: Any, name: Any) -> Any X.findChild(type, name) -> PythonQt.private.QObject (shared captured text)
findChildren function (self, type: Any, name: Any) -> tuple X.findChildren(type, name) -> tuple (shared captured text)
flush function (self) -> bool X.flush() -> bool (shared captured text)
getChar function (self, c: Any) -> bool X.getChar(c) -> bool (shared captured text)
help function (self, *args: Any, **kwargs: Any) -> Any Shows the help of available methods for this class (shared captured text)
hostFound function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.hostFound; argument details are not documented.
inherits function (self, *args: Any, **kwargs: Any) -> Any Returns if the class inherits or is of given type name (shared captured text)
installEventFilter function (self, filterObj: Any) -> Any (shared captured text)
isOpen function (self) -> bool X.isOpen() -> bool (shared captured text)
isReadable function (self) -> bool X.isReadable() -> bool (shared captured text)
isSequential function (self) -> bool X.isSequential() -> bool (shared captured text)
isSignalConnected function (self, signal: Any) -> bool X.isSignalConnected(signal) -> bool (shared captured text)
isTextModeEnabled function (self) -> bool X.isTextModeEnabled() -> bool (shared captured text)
isValid function (self) -> bool X.isValid() -> bool (shared captured text)
isWidgetType function (self) -> bool X.isWidgetType() -> bool (shared captured text)
isWindowType function (self) -> bool X.isWindowType() -> bool (shared captured text)
isWritable function (self) -> bool X.isWritable() -> bool (shared captured text)
killTimer function (self, id: Any) -> Any (shared captured text)
localAddress function (self) -> Any X.localAddress() -> PythonQt.QtNetwork.QHostAddress (shared captured text)
localPort function (self) -> int X.localPort() -> int (shared captured text)
metaObject function (self) -> Any X.metaObject() -> PythonQt.QtCore.QMetaObject (shared captured text)
moveToThread function (self, thread: Any) -> Any (shared captured text)
objectName attribute Any (shared captured text)
objectNameChanged function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.objectNameChanged; argument details are not documented.
open function (self, mode: Any) -> bool X.open(mode) -> bool (shared captured text)
openMode function (self) -> Any (shared captured text)
parent function (self) -> Any X.parent() -> PythonQt.private.QObject (shared captured text)
pauseMode function (self) -> Any Returns the pause mode of this socket. (shared captured text)
peek function (self, maxlen: Any) -> Any X.peek(maxlen) -> PythonQt.QtCore.QByteArray (shared captured text)
peerAddress function (self) -> Any X.peerAddress() -> PythonQt.QtNetwork.QHostAddress (shared captured text)
peerName function (self) -> str X.peerName() -> str (shared captured text)
peerPort function (self) -> int X.peerPort() -> int (shared captured text)
pos function (self) -> int X.pos() -> int (shared captured text)
property function (self, name: Any) -> Any X.property(name) -> object (shared captured text)
proxy function (self) -> Any X.proxy() -> PythonQt.QtNetwork.QNetworkProxy (shared captured text)
proxyAuthenticationRequired function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.proxyAuthenticationRequired; argument details are not documented.
putChar function (self, c: Any) -> bool X.putChar(c) -> bool (shared captured text)
read function (self, maxlen: Any) -> Any X.read(maxlen) -> PythonQt.QtCore.QByteArray (shared captured text)
readAll function (self) -> Any X.readAll() -> PythonQt.QtCore.QByteArray (shared captured text)
readBufferSize function (self) -> int X.readBufferSize() -> int (shared captured text)
readChannelFinished function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.readChannelFinished; argument details are not documented.
readData function (self, data: str, maxlen: int) -> int X.readData(data, maxlen) -> int (shared captured text)
readLine function (self, maxlen: Any) -> Any X.readLine(maxlen) -> PythonQt.QtCore.QByteArray (shared captured text)
readLineData function (self, data: str, maxlen: int) -> int X.readLineData(data, maxlen) -> int (shared captured text)
readyRead function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.readyRead; argument details are not documented.
removeEventFilter function (self, obj: Any) -> Any (shared captured text)
reset function (self) -> bool X.reset() -> bool (shared captured text)
resume function (self) -> None Continues data transfer on the socket. (shared captured text)
seek function (self, pos: Any) -> bool X.seek(pos) -> bool (shared captured text)
sender function (self) -> Any X.sender() -> PythonQt.private.QObject (shared captured text)
senderSignalIndex function (self) -> int X.senderSignalIndex() -> int (shared captured text)
setErrorString function (self, errorString: Any) -> Any (shared captured text)
setLocalAddress function (self, address: Any) -> None Sets the address on the local side of a connection to address. (shared captured text)
setLocalPort function (self, port: int) -> None Sets the port on the local side of a connection to port. (shared captured text)
setObjectName function (self, name: Any) -> Any (shared captured text)
setOpenMode function (self, openMode: Any) -> Any (shared captured text)
setParent function (self, parent: Any) -> Any (shared captured text)
setPauseMode function (self, pauseMode: Any) -> None Controls whether to pause upon receiving a notification. (shared captured text)
setPeerAddress function (self, address: Any) -> None Sets the address of the remote side of the connection to address. (shared captured text)
setPeerName function (self, name: str) -> None Sets the host name of the remote peer to name. (shared captured text)
setPeerPort function (self, port: int) -> None Sets the port of the remote side of the connection to port. (shared captured text)
setProperty function (self, name: Any, value: Any) -> bool X.setProperty(name, value) -> bool (shared captured text)
setProxy function (self, networkProxy: Any) -> None Sets the explicit network proxy for this socket to networkProxy. (shared captured text)
setReadBufferSize function (self, size: int) -> None Sets the size of [QAbstractSocket](https://doc.qt.io/archives/qt-5.15/qabstractsocket.html)'s internal read buffer to be size bytes. (shared captured text)
setSocketDescriptor function (self, socketDescriptor: int, state: Any, openMode: Any) -> bool X.setSocketDescriptor(socketDescriptor, state, openMode) -> bool (shared captured text)
setSocketError function (self, socketError: Any) -> None Sets the type of error that last occurred to socketError. (shared captured text)
setSocketOption function (self, option: Any, value: Any) -> None X.setSocketOption(option, value) (shared captured text)
setSocketState function (self, state: Any) -> None Sets the state of the socket to state. (shared captured text)
setTextModeEnabled function (self, enabled: Any) -> Any (shared captured text)
signalsBlocked function (self) -> bool X.signalsBlocked() -> bool (shared captured text)
size function (self) -> int X.size() -> int (shared captured text)
socketDescriptor function (self) -> int X.socketDescriptor() -> int (shared captured text)
socketOption function (self, option: Any) -> Any X.socketOption(option) -> object (shared captured text)
socketType function (self) -> Any Returns the socket type (TCP, UDP, or other). (shared captured text)
startTimer function (self, interval: Any, timerType: Any) -> int X.startTimer(interval, timerType) -> int (shared captured text)
state function (self) -> Any Returns the state of the socket. (shared captured text)
stateChanged function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QAbstractSocket.stateChanged; argument details are not documented.
thread function (self) -> Any (shared captured text)
timerEvent function (self, event: Any) -> Any (shared captured text)
tr function (self, text: Any, ambig: Any, n: Any) -> str X.tr(text, ambig, n) -> str (shared captured text)
ungetChar function (self, c: Any) -> Any (shared captured text)
waitForBytesWritten function (self, msecs: int) -> bool X.waitForBytesWritten(msecs) -> bool (shared captured text)
waitForConnected function (self, msecs: int) -> bool X.waitForConnected(msecs) -> bool (shared captured text)
waitForDisconnected function (self, msecs: int) -> bool X.waitForDisconnected(msecs) -> bool (shared captured text)
waitForReadyRead function (self, msecs: int) -> bool X.waitForReadyRead(msecs) -> bool (shared captured text)
write function (self, data: Any) -> int X.write(data) -> int (shared captured text)
writeData function (self, data: str, len: int) -> int X.writeData(data, len) -> int (shared captured text)