Skip to content

PythonQt.QtNetwork.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
AnyIPProtocol attribute Any
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.
BindMode attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
BoundState attribute Any
ClosingState attribute Any
ConnectedState attribute Any
ConnectingState attribute Any
ConnectionRefusedError attribute Any
DatagramTooLargeError attribute Any
DefaultForPlatform attribute Any
DontShareAddress attribute Any
HostLookupState attribute Any
HostNotFoundError attribute Any
IPv4Protocol attribute Any
IPv6Protocol attribute Any
KeepAliveOption attribute Any
ListeningState attribute Any
LowDelayOption attribute Any
MulticastLoopbackOption attribute Any
MulticastTtlOption attribute Any
NetworkError attribute Any
NetworkLayerProtocol attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
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
PathMtuSocketOption attribute Any
PauseMode attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
PauseModes attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
PauseNever attribute Any
PauseOnSslErrors attribute Any
ProxyAuthenticationRequiredError attribute Any
ProxyConnectionClosedError attribute Any
ProxyConnectionRefusedError attribute Any
ProxyConnectionTimeoutError attribute Any
ProxyNotFoundError attribute Any
ProxyProtocolError attribute Any
ReadOnly attribute Any (shared captured text)
ReadWrite attribute Any (shared captured text)
ReceiveBufferSizeSocketOption attribute Any
RemoteHostClosedError attribute Any
ReuseAddressHint attribute Any
SctpSocket attribute Any
SendBufferSizeSocketOption attribute Any
ShareAddress attribute Any
SocketAccessError attribute Any
SocketAddressNotAvailableError attribute Any
SocketError attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
SocketOption attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
SocketResourceError attribute Any
SocketState attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
SocketTimeoutError attribute Any
SocketType attribute type Convert a number or string to an integer, or return 0 if no arguments are given.
SslHandshakeFailedError attribute Any
SslInternalError attribute Any
SslInvalidUserDataError attribute Any
TcpSocket attribute Any
TemporaryError attribute Any
Text attribute Any (shared captured text)
Truncate attribute Any (shared captured text)
TypeOfServiceOption attribute Any
UdpSocket attribute Any
Unbuffered attribute Any (shared captured text)
UnconnectedState attribute Any
UnfinishedSocketOperationError attribute Any
UnknownNetworkLayerProtocol attribute Any
UnknownSocketError attribute Any
UnknownSocketType attribute Any
UnsupportedSocketOperationError attribute Any
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.
aboutToClose function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.QAbstractSocket.aboutToClose; argument details are not documented.
atEnd function (self) -> bool X.atEnd() -> bool
bind function (self, address: Any, port: int, mode: Any) -> bool X.bind(address, port, mode) -> bool
blockSignals function (self, b: Any) -> bool X.blockSignals(b) -> bool (shared captured text)
bytesAvailable function (self) -> int X.bytesAvailable() -> int
bytesToWrite function (self) -> int X.bytesToWrite() -> int
bytesWritten function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.QAbstractSocket.bytesWritten; argument details are not documented.
canReadLine function (self) -> bool X.canReadLine() -> bool
channelBytesWritten function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.QAbstractSocket.channelBytesWritten; argument details are not documented.
channelReadyRead function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.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)().
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)
connected function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.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.QtNetwork.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.
disconnected function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.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.
errorOccurred function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.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
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.QtNetwork.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
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
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
localPort function (self) -> int X.localPort() -> int
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.QtNetwork.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.
peek function (self, maxlen: Any) -> Any X.peek(maxlen) -> PythonQt.QtCore.QByteArray (shared captured text)
peerAddress function (self) -> Any X.peerAddress() -> PythonQt.QtNetwork.QHostAddress
peerName function (self) -> str X.peerName() -> str
peerPort function (self) -> int X.peerPort() -> int
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
proxyAuthenticationRequired function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.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
readChannelFinished function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.QAbstractSocket.readChannelFinished; argument details are not documented.
readData function (self, data: str, maxlen: int) -> int X.readData(data, maxlen) -> int
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
readyRead function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.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.
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.
setLocalPort function (self, port: int) -> None Sets the port on the local side of a connection to port.
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.
setPeerAddress function (self, address: Any) -> None Sets the address of the remote side of the connection to address.
setPeerName function (self, name: str) -> None Sets the host name of the remote peer to name.
setPeerPort function (self, port: int) -> None Sets the port of the remote side of the connection to port.
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.
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.
setSocketDescriptor function (self, socketDescriptor: int, state: Any, openMode: Any) -> bool X.setSocketDescriptor(socketDescriptor, state, openMode) -> bool
setSocketError function (self, socketError: Any) -> None Sets the type of error that last occurred to socketError.
setSocketOption function (self, option: Any, value: Any) -> None X.setSocketOption(option, value)
setSocketState function (self, state: Any) -> None Sets the state of the socket to state.
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
socketOption function (self, option: Any) -> Any X.socketOption(option) -> object
socketType function (self) -> Any Returns the socket type (TCP, UDP, or other).
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.
stateChanged function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.QtNetwork.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
waitForConnected function (self, msecs: int) -> bool X.waitForConnected(msecs) -> bool
waitForDisconnected function (self, msecs: int) -> bool X.waitForDisconnected(msecs) -> bool
waitForReadyRead function (self, msecs: int) -> bool X.waitForReadyRead(msecs) -> bool
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