QAbstractSocket¶
The
QAbstractSocket
class provides the base functionality common to all socket types. More…
Inherited by: QSslSocket, QTcpSocket, QUdpSocket
Synopsis¶
Functions¶
def
abort
()def
bind
([port=0[, mode=QAbstractSocket.DefaultForPlatform]])def
bind
(address[, port=0[, mode=QAbstractSocket.DefaultForPlatform]])def
error
()def
flush
()def
isValid
()def
localAddress
()def
localPort
()def
pauseMode
()def
peerAddress
()def
peerName
()def
peerPort
()def
protocolTag
()def
proxy
()def
readBufferSize
()def
setLocalAddress
(address)def
setLocalPort
(port)def
setPauseMode
(pauseMode)def
setPeerAddress
(address)def
setPeerName
(name)def
setPeerPort
(port)def
setProtocolTag
(tag)def
setProxy
(networkProxy)def
setSocketError
(socketError)def
setSocketState
(state)def
socketType
()def
state
()
Virtual functions¶
def
connectToHost
(address, port[, mode=QIODevice.ReadWrite])def
connectToHost
(hostName, port[, mode=QIODevice.ReadWrite[, protocol=AnyIPProtocol]])def
disconnectFromHost
()def
resume
()def
setReadBufferSize
(size)def
setSocketDescriptor
(socketDescriptor[, state=ConnectedState[, openMode=QIODevice.ReadWrite]])def
setSocketOption
(option, value)def
socketDescriptor
()def
socketOption
(option)def
waitForConnected
([msecs=30000])def
waitForDisconnected
([msecs=30000])
Signals¶
def
connected
()def
disconnected
()def
error
(arg__1)def
errorOccurred
(arg__1)def
hostFound
()def
proxyAuthenticationRequired
(proxy, authenticator)def
stateChanged
(arg__1)
Detailed Description¶
QAbstractSocket
is the base class forQTcpSocket
andQUdpSocket
and contains all common functionality of these two classes. If you need a socket, you have two options:
Instantiate
QTcpSocket
orQUdpSocket
.Create a native socket descriptor, instantiate
QAbstractSocket
, and callsetSocketDescriptor()
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.
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 useQAbstractSocket
in more or less the same way regardless of the underlying protocol. Internally,QAbstractSocket
remembers the address and port passed toconnectToHost()
, and functions likeread()
andwrite()
use these values.At any time,
QAbstractSocket
has a state (returned bystate()
). The initial state isUnconnectedState
. After callingconnectToHost()
, the socket first entersHostLookupState
. If the host is found,QAbstractSocket
entersConnectingState
and emits thehostFound()
signal. When the connection has been established, it entersConnectedState
and emitsconnected()
. If an error occurs at any stage,errorOccurred()
is emitted. Whenever the state changes,stateChanged()
is emitted. For convenience,isValid()
returnstrue
if the socket is ready for reading and writing, but note that the socket’s state must beConnectedState
before reading and writing can occur.Read or write data by calling
read()
orwrite()
, or use the convenience functionsreadLine()
andreadAll()
.QAbstractSocket
also inheritsgetChar()
,putChar()
, andungetChar()
fromQIODevice
, which work on single bytes. ThebytesWritten()
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 thereadyRead()
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 toQAbstractSocket
‘s internal read buffer. To limit the size of the read buffer, callsetReadBufferSize()
.To close the socket, call
disconnectFromHost()
.QAbstractSocket
entersClosingState
. After all pending data has been written to the socket,QAbstractSocket
actually closes the socket, entersUnconnectedState
, and emitsdisconnected()
. If you want to abort a connection immediately, discarding all pending data, callabort()
instead. If the remote host closes the connection,QAbstractSocket
will emiterrorOccurred
(RemoteHostClosedError
), during which the socket state will still beConnectedState
, and then thedisconnected()
signal will be emitted.The port and address of the connected peer is fetched by calling
peerPort()
andpeerAddress()
.peerName()
returns the host name of the peer, as passed toconnectToHost()
.localPort()
andlocalAddress()
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:
waitForConnected()
blocks until a connection has been established.
waitForReadyRead()
blocks until new data is available for reading.
waitForBytesWritten()
blocks until one payload of data has been written to the socket.
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()): breakIf
waitForReadyRead()
returnsfalse
, 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 withQTextStream
andQDataStream
‘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
- class PySide2.QtNetwork.QAbstractSocket(socketType, parent)¶
- param parent:
- param socketType:
Creates a new abstract socket of type
socketType
. Theparent
argument is passed toQObject
‘s constructor.See also
- PySide2.QtNetwork.QAbstractSocket.SocketType¶
This enum describes the transport layer protocol.
Constant
Description
QAbstractSocket.TcpSocket
TCP
QAbstractSocket.UdpSocket
UDP
QAbstractSocket.SctpSocket
SCTP
QAbstractSocket.UnknownSocketType
Other than TCP, UDP and SCTP
See also
- PySide2.QtNetwork.QAbstractSocket.NetworkLayerProtocol¶
This enum describes the network layer protocol values used in Qt.
Constant
Description
QAbstractSocket.IPv4Protocol
IPv4
QAbstractSocket.IPv6Protocol
IPv6
QAbstractSocket.AnyIPProtocol
Either IPv4 or IPv6
QAbstractSocket.UnknownNetworkLayerProtocol
Other than IPv4 and IPv6
See also
- PySide2.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
bind()
is already in use and was set to be exclusive.QAbstractSocket.SocketAddressNotAvailableError
The address specified to
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
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
setProxy()
(or the application proxy) was not found.QAbstractSocket.ProxyProtocolError
The connection negotiation with the proxy server failed, because the response from the proxy server could not be understood.
QAbstractSocket.OperationError
An operation was attempted while the socket was in a state that did not permit it.
QAbstractSocket.SslInternalError
The SSL library being used reported an internal error. This is probably the result of a bad installation or misconfiguration of the library.
QAbstractSocket.SslInvalidUserDataError
Invalid data (certificate, key, cypher, etc.) was provided and its use resulted in an error in the SSL library.
QAbstractSocket.TemporaryError
A temporary error occurred (e.g., operation would block and socket is non-blocking).
QAbstractSocket.UnknownSocketError
An unidentified error occurred.
See also
- PySide2.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.
QAbstractSocket.ClosingState
The socket is about to close (data may still be waiting to be written).
QAbstractSocket.ListeningState
For internal use only.
See also
- PySide2.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
connected()
signal from the socket or after having received a new socket from aQTcpServer
.Constant
Description
QAbstractSocket.LowDelayOption
Try to optimize the socket for low latency. For a
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.
QAbstractSocket.TypeOfServiceOption
This option is not supported on Windows. This maps to the IP_TOS socket option. For possible values, see table below.
QAbstractSocket.SendBufferSizeSocketOption
Sets the socket send buffer size in bytes at the OS level. This maps to the SO_SNDBUF socket option. This option does not affect the
QIODevice
orQAbstractSocket
buffers. This enum value has been introduced in Qt 5.3.QAbstractSocket.ReceiveBufferSizeSocketOption
Sets the socket receive buffer size in bytes at the OS level. This maps to the SO_RCVBUF socket option. This option does not affect the
QIODevice
orQAbstractSocket
buffers (seesetReadBufferSize()
). This enum value has been introduced in Qt 5.3.QAbstractSocket.PathMtuSocketOption
Retrieves the Path Maximum Transmission Unit (PMTU) value currently known by the IP stack, if any. Some IP stacks also allow setting the MTU for transmission. This enum value was introduced in Qt 5.11.
Possible values for ** are:
Value
Description
224
Network control
192
Internetwork control
160
CRITIC/ECP
128
Flash override
96
Flash
64
Immediate
32
Priority
0
Routine
See also
New in version 4.6.
- PySide2.QtNetwork.QAbstractSocket.BindFlag¶
This enum describes the different flags you can pass to modify the behavior of
bind()
.Constant
Description
QAbstractSocket.ShareAddress
Allow other services to bind to the same address and port. This is useful when multiple processes share the load of a single service by listening to the same address and port (e.g., a web server with several pre-forked listeners can greatly improve response time). However, because any service is allowed to rebind, this option is subject to certain security considerations. Note that by combining this option with , you will also allow your service to rebind an existing shared address. On Unix, this is equivalent to the SO_REUSEADDR socket option. On Windows, this is the default behavior, so this option is ignored.
QAbstractSocket.DontShareAddress
Bind the address and port exclusively, so that no other services are allowed to rebind. By passing this option to
bind()
, you are guaranteed that on success, your service is the only one that listens to the address and port. No services are allowed to rebind, even if they pass . This option provides more security than , but on certain operating systems, it requires you to run the server with administrator privileges. On Unix and macOS, not sharing is the default behavior for binding an address and port, so this option is ignored. On Windows, this option uses the SO_EXCLUSIVEADDRUSE socket option.QAbstractSocket.ReuseAddressHint
Provides a hint to
QAbstractSocket
that it should try to rebind the service even if the address and port are already bound by another socket. On Windows and Unix, this is equivalent to the SO_REUSEADDR socket option.QAbstractSocket.DefaultForPlatform
The default option for the current platform. On Unix and macOS, this is equivalent to ( + ), and on Windows, it is equivalent to .
- PySide2.QtNetwork.QAbstractSocket.PauseMode¶
This enum describes the behavior of when the socket should hold back with continuing data transfer. The only notification currently supported is
sslErrors()
.Constant
Description
QAbstractSocket.PauseNever
Do not pause data transfer on the socket. This is the default and matches the behavior of Qt 4.
QAbstractSocket.PauseOnSslErrors
Pause data transfer on the socket upon receiving an SSL error notification. I.E.
sslErrors()
.
- PySide2.QtNetwork.QAbstractSocket.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()
close()
- PySide2.QtNetwork.QAbstractSocket.bind([port=0[, mode=QAbstractSocket.DefaultForPlatform]])¶
- Parameters:
port –
quint16
mode –
BindMode
- Return type:
bool
This is an overloaded function.
Binds to
QHostAddress
:Any on portport
, using theBindMode
mode
.By default, the socket is bound using the
DefaultForPlatform
BindMode
. If a port is not specified, a random port is chosen.
- PySide2.QtNetwork.QAbstractSocket.bind(address[, port=0[, mode=QAbstractSocket.DefaultForPlatform]])
- Parameters:
address –
PySide2.QtNetwork.QHostAddress
port –
quint16
mode –
BindMode
- Return type:
bool
Binds to
address
on portport
, using theBindMode
mode
.For UDP sockets, after binding, the signal
readyRead()
is emitted whenever a UDP datagram arrives on the specified address and port. Thus, this function is useful to write UDP servers.For TCP sockets, this function may be used to specify which interface to use for an outgoing connection, which is useful in case of multiple network interfaces.
By default, the socket is bound using the
DefaultForPlatform
BindMode
. If a port is not specified, a random port is chosen.On success, the function returns
true
and the socket entersBoundState
; otherwise it returnsfalse
.
- PySide2.QtNetwork.QAbstractSocket.connectToHost(address, port[, mode=QIODevice.ReadWrite])¶
- Parameters:
address –
PySide2.QtNetwork.QHostAddress
port –
quint16
mode –
OpenMode
This is an overloaded function.
Attempts to make a connection to
address
on portport
.
- PySide2.QtNetwork.QAbstractSocket.connectToHost(hostName, port[, mode=QIODevice.ReadWrite[, protocol=AnyIPProtocol]])
- Parameters:
hostName – str
port –
quint16
mode –
OpenMode
protocol –
NetworkLayerProtocol
Attempts to make a connection to
hostName
on the givenport
. Theprotocol
parameter can be used to specify which network protocol to use (eg. IPv4 or IPv6).The socket is opened in the given
openMode
and first entersHostLookupState
, then performs a host name lookup ofhostName
. If the lookup succeeds,hostFound()
is emitted andQAbstractSocket
entersConnectingState
. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established,QAbstractSocket
entersConnectedState
and emitsconnected()
.At any point, the socket can emit
errorOccurred()
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., “example.com”).QAbstractSocket
will do a lookup only if required.port
is in native byte order.
- PySide2.QtNetwork.QAbstractSocket.connected()¶
- PySide2.QtNetwork.QAbstractSocket.disconnectFromHost()¶
Attempts to close the socket. If there is pending data waiting to be written,
QAbstractSocket
will enterClosingState
and wait until all data has been written. Eventually, it will enterUnconnectedState
and emit thedisconnected()
signal.See also
- PySide2.QtNetwork.QAbstractSocket.disconnected()¶
- PySide2.QtNetwork.QAbstractSocket.error()¶
- Return type:
Returns the type of error that last occurred.
See also
state()
errorString()
- PySide2.QtNetwork.QAbstractSocket.error(arg__1)
- Parameters:
arg__1 –
SocketError
Note
This function is deprecated.
- PySide2.QtNetwork.QAbstractSocket.errorOccurred(arg__1)¶
- Parameters:
arg__1 –
SocketError
- PySide2.QtNetwork.QAbstractSocket.flush()¶
- Return type:
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
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, becauseQAbstractSocket
will start sending data automatically once control goes back to the event loop. In the absence of an event loop, callwaitForBytesWritten()
instead.See also
write()
waitForBytesWritten()
- PySide2.QtNetwork.QAbstractSocket.hostFound()¶
- PySide2.QtNetwork.QAbstractSocket.isValid()¶
- Return type:
bool
Returns
true
if the socket is valid and ready for use; otherwise returnsfalse
.Note
The socket’s state must be
ConnectedState
before reading and writing can occur.See also
- PySide2.QtNetwork.QAbstractSocket.localAddress()¶
- Return type:
Returns the host address of the local socket if available; otherwise returns
Null
.This is normally the main IP address of the host, but can be
LocalHost
(127.0.0.1) for connections to the local host.See also
- PySide2.QtNetwork.QAbstractSocket.localPort()¶
- Return type:
quint16
Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.
See also
- PySide2.QtNetwork.QAbstractSocket.pauseMode()¶
- Return type:
PauseModes
Returns the pause mode of this socket.
See also
- PySide2.QtNetwork.QAbstractSocket.peerAddress()¶
- Return type:
Returns the address of the connected peer if the socket is in
ConnectedState
; otherwise returnsNull
.
- PySide2.QtNetwork.QAbstractSocket.peerName()¶
- Return type:
str
Returns the name of the peer as specified by
connectToHost()
, or an emptyQString
ifconnectToHost()
has not been called.See also
- PySide2.QtNetwork.QAbstractSocket.peerPort()¶
- Return type:
quint16
Returns the port of the connected peer if the socket is in
ConnectedState
; otherwise returns 0.See also
- PySide2.QtNetwork.QAbstractSocket.protocolTag()¶
- Return type:
str
Returns the protocol tag for this socket. If the protocol tag is set then this is passed to
QNetworkProxyQuery
when this is created internally to indicate the protocol tag to be used.See also
- PySide2.QtNetwork.QAbstractSocket.proxy()¶
- Return type:
Returns the network proxy for this socket. By default
DefaultProxy
is used, which means this socket will query the default proxy settings for the application.See also
- PySide2.QtNetwork.QAbstractSocket.proxyAuthenticationRequired(proxy, authenticator)¶
- Parameters:
proxy –
PySide2.QtNetwork.QNetworkProxy
authenticator –
PySide2.QtNetwork.QAuthenticator
- PySide2.QtNetwork.QAbstractSocket.readBufferSize()¶
- Return type:
int
Returns the size of the internal read buffer. This limits the amount of data that the client can receive before you call
read()
orreadAll()
.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()
read()
- PySide2.QtNetwork.QAbstractSocket.resume()¶
Continues data transfer on the socket. This method should only be used after the socket has been set to pause upon notifications and a notification has been received. The only notification currently supported is
sslErrors()
. Calling this method if the socket is not paused results in undefined behavior.See also
- PySide2.QtNetwork.QAbstractSocket.setLocalAddress(address)¶
- Parameters:
address –
PySide2.QtNetwork.QHostAddress
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 thelocalAddress()
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.,
bind()
).See also
- PySide2.QtNetwork.QAbstractSocket.setLocalPort(port)¶
- Parameters:
port –
quint16
Sets the port on the local side of a connection to
port
.You can call this function in a subclass of
QAbstractSocket
to change the return value of thelocalPort()
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.,
bind()
).
- PySide2.QtNetwork.QAbstractSocket.setPauseMode(pauseMode)¶
- Parameters:
pauseMode –
PauseModes
Controls whether to pause upon receiving a notification. The
pauseMode
parameter specifies the conditions in which the socket should be paused. The only notification currently supported issslErrors()
. If set toPauseOnSslErrors
, data transfer on the socket will be paused and needs to be enabled explicitly again by callingresume()
. By default this option is set toPauseNever
. This option must be called before connecting to the server, otherwise it will result in undefined behavior.See also
- PySide2.QtNetwork.QAbstractSocket.setPeerAddress(address)¶
- Parameters:
address –
PySide2.QtNetwork.QHostAddress
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 thepeerAddress()
function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.See also
- PySide2.QtNetwork.QAbstractSocket.setPeerName(name)¶
- Parameters:
name – str
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 thepeerName()
function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.See also
- PySide2.QtNetwork.QAbstractSocket.setPeerPort(port)¶
- Parameters:
port –
quint16
Sets the port of the remote side of the connection to
port
.You can call this function in a subclass of
QAbstractSocket
to change the return value of thepeerPort()
function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.See also
- PySide2.QtNetwork.QAbstractSocket.setProtocolTag(tag)¶
- Parameters:
tag – str
Sets the protocol tag for this socket to
tag
.See also
- PySide2.QtNetwork.QAbstractSocket.setProxy(networkProxy)¶
- Parameters:
networkProxy –
PySide2.QtNetwork.QNetworkProxy
Sets the explicit network proxy for this socket to
networkProxy
.To disable the use of a proxy for this socket, use the
NoProxy
proxy type:socket.setProxy(QNetworkProxy.NoProxy)
The default value for the proxy is
DefaultProxy
, which means the socket will use the application settings: if a proxy is set withsetApplicationProxy
, it will use that; otherwise, if a factory is set withsetApplicationProxyFactory
, it will query that factory with typeTcpSocket
.See also
- PySide2.QtNetwork.QAbstractSocket.setReadBufferSize(size)¶
- Parameters:
size – int
Sets the size of
QAbstractSocket
‘s internal read buffer to besize
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
usesQAbstractSocket
‘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 onQUdpSocket
has no effect.See also
readBufferSize()
read()
- PySide2.QtNetwork.QAbstractSocket.setSocketDescriptor(socketDescriptor[, state=ConnectedState[, openMode=QIODevice.ReadWrite]])¶
- Parameters:
socketDescriptor –
qintptr
state –
SocketState
openMode –
OpenMode
- Return type:
bool
Initializes
QAbstractSocket
with the native socket descriptorsocketDescriptor
. Returnstrue
ifsocketDescriptor
is accepted as a valid socket descriptor; otherwise returnsfalse
. The socket is opened in the mode specified byopenMode
, and enters the socket state specified bysocketState
. Read and write buffers are cleared, discarding any pending data.Note
It is not possible to initialize two abstract sockets with the same native socket descriptor.
See also
- PySide2.QtNetwork.QAbstractSocket.setSocketError(socketError)¶
- Parameters:
socketError –
SocketError
Sets the type of error that last occurred to
socketError
.See also
setSocketState()
setErrorString()
- PySide2.QtNetwork.QAbstractSocket.setSocketOption(option, value)¶
- Parameters:
option –
SocketOption
value – object
Sets the given
option
to the value described byvalue
.Note
On Windows Runtime,
KeepAliveOption
must be set before the socket is connected.See also
- PySide2.QtNetwork.QAbstractSocket.setSocketState(state)¶
- Parameters:
state –
SocketState
Sets the state of the socket to
state
.See also
- PySide2.QtNetwork.QAbstractSocket.socketDescriptor()¶
- Return type:
qintptr
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 inUnconnectedState
.See also
- PySide2.QtNetwork.QAbstractSocket.socketOption(option)¶
- Parameters:
option –
SocketOption
- Return type:
object
Returns the value of the
option
option.See also
- PySide2.QtNetwork.QAbstractSocket.socketType()¶
- Return type:
Returns the socket type (TCP, UDP, or other).
See also
- PySide2.QtNetwork.QAbstractSocket.state()¶
- Return type:
Returns the state of the socket.
See also
- PySide2.QtNetwork.QAbstractSocket.stateChanged(arg__1)¶
- Parameters:
arg__1 –
SocketState
- PySide2.QtNetwork.QAbstractSocket.waitForConnected([msecs=30000])¶
- Parameters:
msecs – int
- Return type:
bool
Waits until the socket is connected, up to
msecs
milliseconds. If the connection has been established, this function returnstrue
; otherwise it returnsfalse
. In the case where it returnsfalse
, you can callerror()
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.
Note
This function may fail randomly on Windows. Consider using the event loop and the
connected()
signal if your software will run on Windows.See also
- PySide2.QtNetwork.QAbstractSocket.waitForDisconnected([msecs=30000])¶
- Parameters:
msecs – int
- Return type:
bool
Waits until the socket has disconnected, up to
msecs
milliseconds. If the connection was successfully disconnected, this function returnstrue
; otherwise it returnsfalse
(if the operation timed out, if an error occurred, or if thisQAbstractSocket
is already disconnected). In the case where it returnsfalse
, you can callerror()
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.
Note
This function may fail randomly on Windows. Consider using the event loop and the
disconnected()
signal if your software will run on Windows.See also
disconnectFromHost()
close()
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.