Socket Python Reference Documentation
Socket
Current Version: 11.5.0
Chilkat.Socket
Connect to remote hosts and ports for custom protocols or direct
socket-level communication.
Use SSL/TLS, inspect certificates, provide client certificates, and
control TLS-related behavior when secure sockets are required.
Send and receive strings, byte data, files, fixed-size blocks,
delimiter-terminated messages, or protocol-specific data patterns.
Listen for and accept incoming client connections when implementing
simple socket servers or custom listener workflows.
Route socket connections through HTTP proxies, SOCKS proxies, or
SSH-tunneled connections when network topology requires it.
Configure connection and read/write timeouts, monitor counters, and use
logs and
For an extended overview, see
Socket Class Overview.
Build custom TCP, TLS, proxy, SSH-tunneled, client/server, and socket-level protocols.
Chilkat.Socket is the low-level networking class for
applications that need direct control over TCP and TLS communication. It can
connect as a client, accept incoming connections, send and receive text or
binary data, use proxies or SSH tunnels, configure TLS certificates and
socket options, manage timeouts, work with socket sets, collect performance
counters, and produce detailed diagnostics and session logs for custom
protocol troubleshooting.
TCP client connections
TLS and certificates
Send and receive data
Server-side sockets
Proxy and SSH tunneling
Timeouts and diagnostics
LastErrorText to diagnose connection or protocol
failures.
Socket when the application is implementing a custom
protocol or needs lower-level control than higher-level Chilkat classes
provide. Configure the connection, TLS, proxy, timeout, and logging options,
connect or accept a client, then send and receive data according to the
protocol. Use higher-level classes such as Http,
Rest, Ssh, SFtp, or
MailMan when the protocol is already directly supported.
Object Creation
obj = chilkat2.Socket()
Properties
AbortCurrent
Set this property to True to request cancellation of the method currently executing on this object. It affects operations that can block or take significant time, such as network reads, writes, connection establishment, and long-running asynchronous methods. Fast, nonblocking methods may finish before the cancellation request is observed.
After an operation aborts, Chilkat automatically resets this property to False. If no operation is running, the next method call clears a previously set value before it begins.
LastErrorText describes the abort.AcceptFailReason
Contains a numeric reason code when AcceptNext or the deprecated AcceptNextConnection method fails. Examine this property immediately after the failed accept operation.
| Code | Meaning |
|---|---|
| 0 | Success. |
| 1 | An asynchronous accept operation is already in progress. |
| 3 | Internal failure, such as an allocation failure. |
| 5 | No incoming connection was accepted before the wait interval expired. |
| 6 | The operation was aborted by the application. |
| 9 | An unspecified fatal socket error occurred. |
| 20 | The socket has not first been bound and placed into listening mode. |
| 99 | The Chilkat component is not unlocked. |
| 100 | TLS internal error. |
| 102 | Unexpected TLS handshake message. |
| 109 | Failed to read TLS handshake messages. |
| 114 | Failed to send the ChangeCipherSpec message. |
| 115 | Failed to send the Finished message. |
| 116 | The client's Finished message was invalid. |
| 117 | Unable to agree on a TLS protocol version. |
| 118 | Unable to agree on a cipher suite. |
| 119 | Failed to read the client's ClientHello message. |
| 120 | Failed to send TLS handshake messages. |
| 121 | Failed to process the client certificate message. |
| 122 | Failed to process the client certificate URL message. |
| 123 | Failed to process the client key-exchange message. |
| 124 | Failed to process the CertificateVerify message. |
| 125 | An SSL 2.0 connection attempt was received and rejected. |
AlpnProtocol
Specifies the application-layer protocol name offered in the TLS ALPN extension, such as h2 or http/1.1. Leave it empty when ALPN is not required.
BandwidthThrottleDown
Limits receive throughput to approximately the specified number of bytes per second. The default value is 0, which disables receive throttling.
BandwidthThrottleUp
Limits send throughput to approximately the specified number of bytes per second. The default value is 0, which disables send throttling.
BigEndian
Controls the byte order used by SendCount and ReceiveCount. The default is True, which uses big-endian byte order (network byte order). Set it to False to use little-endian byte order.
SendInt16, SendInt32, ReceiveInt16, and ReceiveInt32 methods receive their byte-order choice as an argument.ClientIpAddress
Specifies the numeric local IP address to bind before initiating an outbound connection. Use this on a multihomed computer when the connection must originate from a particular network interface or local address. Leave it empty to let the operating system choose the appropriate local address.
ClientPort
Specifies the local TCP port to bind before initiating an outbound connection. The default value is 0, which asks the operating system to choose an available ephemeral port.
ConnectFailReason
Contains a numeric reason code when Connect fails. Examine this property immediately after the failed connection attempt.
| Code | Meaning |
|---|---|
| 0 | Success. |
| 1 | The hostname is empty. |
| 2 | DNS lookup failed. |
| 3 | DNS lookup timed out. |
| 4 | The operation was aborted by the application. |
| 5 | Internal failure. |
| 6 | The TCP connection attempt timed out. |
| 7 | The connection was rejected or otherwise could not be established. |
| 100 | TLS internal error. |
| 101 | Failed to send ClientHello. |
| 102 | Unexpected TLS handshake message. |
| 103 | Failed to read ServerHello. |
| 104 | The server did not provide a certificate. |
| 105 | Unexpected TLS protocol version. |
| 106 | Server-certificate verification failed. |
| 107 | The negotiated TLS protocol version was not permitted. |
| 108 | An application-defined server-certificate requirement failed. |
| 109 | Failed to read TLS handshake messages. |
| 110 | Failed to send the client-certificate message. |
| 111 | Failed to send the client key-exchange message. |
| 112 | The client certificate's private key was not accessible. |
| 113 | Failed to send the client CertificateVerify message. |
| 114 | Failed to send the ChangeCipherSpec message. |
| 115 | Failed to send the Finished message. |
| 116 | The server's Finished message was invalid. |
Connect is distinct from DNS, proxy, and TLS-handshake inactivity limits. See MaxReadIdleMs and MaxSendIdleMs.DebugLogFilePath
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
ElapsedSeconds
Returns the whole number of seconds elapsed since the most recent call to StartTiming. It returns 0 if timing has not been started or less than one second has elapsed.
HttpProxyAuthMethod
Specifies the authentication method used with an HTTP proxy. Supported values are Basic and NTLM. Leave it empty when the proxy does not require authentication.
HttpProxyDomain
Specifies the optional Windows domain used for NTLM authentication to an HTTP proxy. It is ignored unless HttpProxyAuthMethod is NTLM.
HttpProxyForHttp
Set this property to True when the proxied connection will carry HTTP requests, such as when a Rest object uses this socket through UseConnection. The default is False.
An HTTP client can communicate with a proxy differently from a non-HTTP protocol. For example, plain HTTP commonly sends an absolute request URI to the proxy, whereas other protocols generally require an HTTP CONNECT tunnel.
HttpProxyHostname
Specifies the hostname or numeric IP address of the HTTP proxy. Leave it empty to connect directly without an HTTP proxy.
topHttpProxyPassword
Specifies the password used to authenticate with the HTTP proxy. It is used together with HttpProxyUsername and the selected HttpProxyAuthMethod.
HttpProxyPort
Specifies the TCP port of the HTTP proxy. Common values include 8080 and 3128, but the correct port is determined by the proxy configuration.
HttpProxyUsername
Specifies the username used to authenticate with the HTTP proxy. It is ignored when the proxy does not require authentication.
topIsConnected
Returns True when the socket is in its last known connected state; otherwise returns False. Explicitly closing the socket updates this property immediately.
True until a read, write, or other socket operation detects the loss. Treat it as a cached state indicator, not a guarantee that the next operation will succeed.KeepAlive
Controls the operating system SO_KEEPALIVE option for the underlying TCP socket. The default is True.
KeepSessionLog
Set this property to True to record bytes sent and received in SessionLog. The default is False. Use SessionLogEncoding to choose how bytes are rendered.
LastErrorHtml
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodFailed
Returns True if the most recently called method on this object failed; otherwise returns False. This is especially useful for methods whose normal return type, such as a string, byte array, or integer, can otherwise make success and failure difficult to distinguish.
LastMethodSuccess
Indicates the success or failure of the most recent method call: True means success, False means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
ListenIpv6
Controls the address family used by BindAndListen and BindAndListenPortRange. The default is False for an IPv4 listener. Set it to True to create an IPv6 listener.
ListenPort
Returns the port on which the socket is listening. This is especially useful after calling BindAndListen with port 0, which asks the operating system to select an available port.
LocalIpAddress
Returns the local IP address assigned to the bound or connected socket. For an outbound connection, this is the source address selected or explicitly bound. For a listener, it is the local address on which the socket is listening.
topLocalPort
Returns the local TCP port assigned to the bound or connected socket. When binding to port 0, use this property or ListenPort after success to discover the operating-system-selected port.
MaxReadIdleMs
Specifies the maximum number of milliseconds a read-related operation may remain without receiving additional data. Each arrival of data represents progress and restarts the inactivity interval. The default is 0, which waits indefinitely.
This timeout applies to socket receive methods and to other operations that must read protocol data, including DNS, proxy negotiation, TLS handshakes, and SSH tunnel setup where applicable.
MaxSendIdleMs
Specifies the maximum number of milliseconds a send-related operation may remain without making additional write progress. The default is 0, which waits indefinitely.
MyIpAddress
Returns a local IP address for the computer. On a multihomed system, this is a default or preferred local address and may not be the address used by a particular connection.
LocalIpAddress and LocalPort.NumBytesAvailable
Returns the number of bytes immediately available to the socket layer without waiting. On a TLS connection, the value can include encrypted TLS record overhead and therefore does not necessarily equal the amount of application plaintext available.
NumReceivedClientCerts
Returns the number of client certificates received during the TLS handshake on an accepted server-side connection. Retrieve certificates by calling GetRcvdClientCert with indexes from 0 through NumReceivedClientCerts - 1.
AcceptNext, not on the listener socket. Client certificates are normally present only when the server requested mutual TLS authentication.NumSocketsInSet
Returns the number of sockets contained in this socket set. A normal Socket object becomes a socket set after one or more calls to TakeSocket.
Use SelectForReading or SelectForWriting to find ready sockets, then use SelectorReadIndex, SelectorWriteIndex, and SelectorIndex to route subsequent operations to a contained socket.
NumSslAcceptableClientCAs
After a TLS server requests a client certificate, returns the number of acceptable certificate-authority distinguished names sent by that server. Use GetSslAcceptableClientCaDn to retrieve each DN by zero-based index.
ObjectId
Returns the unique identifier assigned to this socket object. The identifier is included in event callbacks so an application can associate a callback with the originating object.
PreferIpv6
Controls address-family preference when a hostname resolves to both IPv4 and IPv6 addresses. The default is False, which prefers IPv4; set it to True to prefer IPv6.
For listener sockets in current Chilkat versions, enabling IPv6 can use dual-stack behavior when supported by the operating system, allowing one listener to accept both IPv6 and IPv4 connections.
RcvBytesPerSec
Returns the average raw receive rate, in bytes per second, since receive performance measurement began or was last reset. The measurement includes TLS or SSH framing overhead. Call ResetPerf with True to restart receive measurement.
ReceivedCount
Tracks the cumulative number of application bytes read from the underlying socket by receive operations. The application may assign 0 at any time to restart the count.
The count can be greater than the number of bytes returned by a particular method because Chilkat may read beyond a delimiter and buffer the excess for a later receive call. TLS and SSH framing overhead is not included.
RcvBytesPerSec when measuring raw transfer rate including protocol overhead.ReceivedInt
Contains the value produced by the most recent successful call to ReceiveByte, ReceiveInt16, or ReceiveInt32. The signedness and byte order are determined by the arguments supplied to that receive method.
ReceiveFailReason
Contains a numeric reason code when a receive method fails. Examine it immediately after the failed receive operation.
| Code | Meaning |
|---|---|
| 0 | Success. |
| 1 | An asynchronous receive operation is already in progress. |
| 2 | The socket is not connected. |
| 3 | Internal failure, such as an allocation failure. |
| 4 | Invalid parameters were supplied. |
| 5 | No additional data arrived within MaxReadIdleMs. |
| 6 | The operation was aborted by the application. |
| 7 | The peer reset the connection. |
| 8 | The host operating system aborted the established connection. |
| 9 | An unspecified fatal socket error occurred. |
| 10 | The peer closed the connection. |
ReceivePacketSize
Specifies the internal read size, in bytes, used by receive methods that do not request an exact byte count, such as ReceiveBytes and ReceiveString. The default is 4096.
RemoteIpAddress
Returns the numeric IP address of the connected peer. This is the address actually used by the established connection, which may differ from the hostname originally supplied to Connect.
RemotePort
Returns the TCP port of the connected peer.
topRequireSslCertVerify
When True, a TLS client connection requires successful verification of the server certificate, including certificate validity and trust-chain checks. The connection fails when verification cannot be completed. The default is False.
TlsPinSet when the application also requires an exact SPKI pin match.SelectorIndex
For a socket set, selects the contained socket to which ordinary method calls and property access are routed. Indexing is zero-based and must be within 0 through NumSocketsInSet - 1.
SelectForReading or SelectForWriting, copy the desired ready index from SelectorReadIndex or SelectorWriteIndex into this property before reading or writing.SelectorReadIndex
Selects an entry in the read-ready result set produced by SelectForReading. Set this property to a zero-based value from 0 through one less than the number returned by SelectForReading; the corresponding contained-socket index can then be obtained or selected according to the socket-set workflow.
SelectorWriteIndex
Selects an entry in the write-ready result set produced by SelectForWriting. Set it to a zero-based value from 0 through one less than the number returned by SelectForWriting.
SendBytesPerSec
Returns the average raw send rate, in bytes per second, since send performance measurement began or was last reset. The measurement includes TLS or SSH framing overhead. Call ResetPerf with False to restart send measurement.
SendFailReason
Contains a numeric reason code when a send method fails. Examine it immediately after the failed send operation.
| Code | Meaning |
|---|---|
| 0 | Success. |
| 1 | An asynchronous send operation is already in progress. |
| 2 | The socket is not connected. |
| 3 | Internal failure, such as an allocation failure. |
| 4 | Invalid parameters were supplied. |
| 5 | The socket remained unable to make send progress for longer than MaxSendIdleMs. |
| 6 | The operation was aborted by the application. |
| 7 | The peer reset the connection. |
| 8 | The host operating system aborted the established connection. |
| 9 | An unspecified fatal socket error occurred. |
| 10 | The peer closed the connection. |
| 11 | Text or encoded input could not be converted or decoded, such as an invalid StringCharset conversion or malformed encoded data. |
SendPacketSize
Specifies the internal chunk size used when sending a large amount of data over a plain TCP connection. The default is 65535 bytes. TLS connections use TLS record handling rather than this setting.
SessionLog
Returns the accumulated send/receive session log when KeepSessionLog is True. Use SessionLogEncoding to choose an escaped or hexadecimal representation and ClearSessionLog to reset it.
SessionLogEncoding
Controls how bytes are rendered in SessionLog. The default is esc.
| Value | Format |
|---|---|
esc | Compact C-style escaped text. Printable ASCII remains readable; control and nonprintable bytes are escaped, such as \r, \n, and \xHH. |
hex | Every byte is represented in hexadecimal, which is larger but unambiguous for binary protocols. |
SniHostname
Overrides the Server Name Indication (SNI) hostname sent in the TLS ClientHello. Normally Chilkat automatically uses the domain name supplied to Connect. Set this property when connecting to a numeric IP address or alternate endpoint while the TLS server expects a particular virtual-host name.
SocksHostname
Specifies the hostname or numeric IP address of the SOCKS proxy. It is used only when SocksVersion is 4 or 5.
SocksPassword
Specifies the password for SOCKS5 username/password authentication. SOCKS4 does not define a password field, so this property is ignored for SOCKS4.
SocksPort
Specifies the TCP port of the SOCKS proxy. The default is 1080. It is used only when SocksVersion is 4 or 5.
SocksUsername
Specifies the SOCKS proxy username. For SOCKS4 it is the user ID sent in the request; for SOCKS5 it is used when username/password authentication is negotiated.
topSocksVersion
Selects whether connections are routed through a SOCKS proxy.
| Value | Behavior |
|---|---|
| 0 | Do not use a SOCKS proxy. This is the default. |
| 4 | Connect through a SOCKS4 proxy. |
| 5 | Connect through a SOCKS5 proxy. |
SoRcvBuf
Requests the operating-system receive-buffer size for the TCP socket. The default requested value is 4194304 bytes. Most applications should leave it unchanged.
SoReuseAddr
Controls the SO_REUSEADDR option for a socket that will bind and listen. The default is True. Set it before BindAndListen, BindAndListenPortRange, or InitSslServer.
SO_REUSEADDR differs across operating systems. It can help restart a listener after a previous connection, but it is not a portable substitute for exclusive-port ownership.SoSndBuf
Requests the operating-system send-buffer size for the TCP socket. The default requested value is 262144 bytes. Most applications should leave it unchanged.
Ssl
Controls whether incoming connections accepted by this listener must complete a TLS handshake. The default is False. Set it to True for a TLS server listener.
TlsVersion to determine whether the current or most recent connection negotiated TLS. Configure the server certificate with InitSslServer before accepting TLS clients.SslAllowedCiphers
Restricts the cipher suites permitted for TLS connections. The default empty string allows all cipher suites implemented and enabled by the Chilkat build. To restrict negotiation, provide a comma-separated list of supported cipher-suite names in preference order.
The property also recognizes the policy keywords rsa1024, rsa2048, secure-renegotiation, and best-practices. Legacy filter keywords such as aes256-cbc, aes128-cbc, 3des-cbc, and rc4 remain recognized for compatibility, but explicit suites or best-practices are clearer.
best-practices can change with Chilkat versions and platform capabilities. Avoid obsolete suites based on RC4, DES, or 3DES. The server ultimately selects from the suites offered by the client.SslProtocol
Controls the TLS protocol versions permitted for secure connections. Accepted values include default, an exact version such as TLS 1.2 or TLS 1.3, and minimum-version forms such as TLS 1.2 or higher. Legacy values for older protocols are retained for compatibility.
The default value is default, which lets Chilkat negotiate an appropriate mutually supported version according to the library and platform security policy. An exact-version setting causes the connection to fail unless that exact version is negotiated.
TLS 1.2 or higher or the current default policy.StringCharset
Specifies the character encoding used by text-oriented socket methods. Examples include utf-8, windows-1252, shift_jis, and iso-8859-1. The default is ansi.
Sending methods such as SendString and SendSb encode text using this charset. String receive methods decode incoming bytes from this charset, including ReceiveString, ReceiveSb, ReceiveToCRLF, and delimiter-based string methods.
TcpNoDelay
Controls the TCP_NODELAY option. The default is False, allowing the Nagle algorithm. Set it to True to send small writes with lower latency rather than waiting to coalesce them.
TlsCipherSuite
Returns the cipher suite negotiated for the current or most recent successful TLS connection, for example TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384. It is empty before a TLS connection has been established or after a connection attempt that did not negotiate TLS.
TlsPinSet
Specifies one or more expected SubjectPublicKeyInfo (SPKI) fingerprints for TLS public-key pinning. The TLS handshake fails unless the certificate presented by the server matches one of the listed pins.
Use the format hash_algorithm, encoding, fingerprint1, fingerprint2, .... For example:
sha256, base64, lKg1SIqyhPSK19tlPbjl8s02yChsVTDklQpkMCHvsTE=
Common choices are sha256 with base64 or hex. Other Chilkat hash and binary-encoding names are also accepted.
TlsVersion
Returns the protocol version negotiated for the current or most recent successful TLS connection, such as TLS 1.2 or TLS 1.3. It is empty when no TLS session has been established.
UncommonOptions
Provides comma-separated compatibility or platform-specific options. The default is the empty string and should normally remain unchanged.
| Keyword | Behavior |
|---|---|
ProtectFromVpn | On Android, attempts to route the socket outside an active VPN. |
EnableTls13 | Historical compatibility option introduced when TLS 1.3 was not yet enabled by default. It is generally unnecessary in current versions. |
ListenAllNetworkInterfaces | Causes a listener to bind to all IPv4 interfaces (0.0.0.0) instead of loopback (127.0.0.1). |
UserData
Stores arbitrary application text with the socket object. Chilkat does not transmit, interpret, or otherwise use this value. It is useful for associating a label, connection ID, or other application metadata with a socket.
topVerboseLogging
If set to True, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is False. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
Methods
AcceptNext
Waits for and accepts the next incoming connection on a socket previously configured by BindAndListen or BindAndListenPortRange. maxWaitMs is the maximum time to wait for an incoming TCP connection; use 0 to wait indefinitely. On success, socket is populated with the accepted connection.
maxWaitMs governs the wait for an incoming connection, while TLS read and write inactivity are governed by MaxReadIdleMs and MaxSendIdleMs. Set finite values to prevent an unresponsive client from holding the handshake indefinitely.socket, not on the listener.Returns True for success, False for failure.
AcceptNextAsync (1)
Creates an asynchronous task to call the AcceptNext method with the arguments provided.
Returns None on failure
AddSslAcceptableClientCaDn
Adds a certificate-authority distinguished name to the list advertised or accepted by a TLS server when requesting a client certificate for mutual TLS. Call this method one or more times before InitSslServer.
If no CA distinguished names are added, client certificates issued by any root CA are accepted by this CA-name filter.
Returns True for success, False for failure.
BindAndListen
Binds a TCP listener to port and places it into listening mode. Use AcceptNext to accept incoming connections after this method succeeds.
backLog is the requested operating-system queue length for connections that have completed or are completing the TCP handshake but have not yet been accepted. It is a queue hint, not a limit on the total number of clients the application can serve.
Pass 0 for port to let the operating system select an available port, then read ListenPort. Set ListenIpv6 before calling this method when an IPv6 listener is required.
Returns True for success, False for failure.
BindAndListenAsync (1)
Creates an asynchronous task to call the BindAndListen method with the arguments provided.
Returns None on failure
BindAndListenPortRange
Searches the inclusive range beginPort through endPort for an available TCP port, binds it, and begins listening. backLog is the requested operating-system pending-connection queue length.
Set ListenIpv6 before calling when an IPv6 listener is required. The method returns the selected port, or -1 when no port can be bound or another error occurs.
AcceptNext after a port is successfully selected.BindAndListenPortRangeAsync (1)
Creates an asynchronous task to call the BindAndListenPortRange method with the arguments provided.
Returns None on failure
BuildHttpGetRequest
Builds and returns a simple HTTP GET request for url. The method only constructs the request text; it does not connect, send the request, follow redirects, or read a response.
Http or Rest class for normal HTTP work. This helper is intended for low-level socket examples or custom HTTP handling.Returns None on failure
CheckWriteable
Waits up to maxWaitMs for the connected socket to become writable. Use 0 to poll without waiting.
| Return value | Meaning |
|---|---|
| 1 | The socket is connected and currently writable. |
| 0 | The wait timed out or the operation was aborted. |
| -1 | The socket is not connected or an error occurred. |
CheckWriteableAsync (1)
Creates an asynchronous task to call the CheckWriteable method with the arguments provided.
Returns None on failure
ClearSessionLog
Clears the accumulated text returned by SessionLog. It does not change KeepSessionLog or close the connection.
Close
Attempts to gracefully terminate and close the current TCP, TLS, or SSH channel connection. maxWaitMs limits how long the method waits for clean shutdown processing before completing.
IsConnected is False. A graceful close cannot guarantee that the remote application processed all previously sent data.Returns True for success, False for failure.
topCloseAsync (1)
Creates an asynchronous task to call the Close method with the arguments provided.
Returns None on failure
Connect
Establishes a TCP connection to hostname:port. Set ssl to True to perform a TLS handshake immediately after the TCP connection succeeds; set it to False for plain TCP. The hostname may be a DNS name or a numeric IPv4 or IPv6 address.
maxWaitMs limits the TCP connection attempt itself. DNS resolution, proxy negotiation, SSH tunneling, and TLS-handshake reads and writes use the applicable MaxReadIdleMs and MaxSendIdleMs settings.
Connection options such as ClientIpAddress, ClientPort, proxy settings, PreferIpv6, TLS policy, SNI, ALPN, certificate verification, and client certificates must be configured before calling this method.
Returns True for success, False for failure.
ConnectAsync (1)
Creates an asynchronous task to call the Connect method with the arguments provided.
Returns None on failure
ConvertFromSsl
Ends the TLS layer while leaving the underlying TCP connection open for subsequent unencrypted communication. This is the reverse of a STARTTLS-style upgrade.
Returns True for success, False for failure.
topConvertFromSslAsync (1)
Creates an asynchronous task to call the ConvertFromSsl method with the arguments provided.
Returns None on failure
ConvertToSsl
Upgrades an already connected plain TCP socket to TLS by performing a client-side TLS handshake over the existing connection.
Returns True for success, False for failure.
ConvertToSslAsync (1)
Creates an asynchronous task to call the ConvertToSsl method with the arguments provided.
Returns None on failure
DnsCacheClear
Clears Chilkat's process-wide in-memory DNS cache. Subsequent hostname resolutions perform a new lookup as needed.
DnsLookup
Resolves hostname and returns a numeric IP address. maxWaitMs is the maximum time to wait; use 0 to wait indefinitely.
PreferIpv6; it is not a complete DNS-record enumeration.Returns None on failure
DnsLookupAsync (1)
Creates an asynchronous task to call the DnsLookup method with the arguments provided.
Returns None on failure
DupSocket
Populates dest with another socket object that shares the same underlying TCP or TLS connection as this object. Reads and writes through either object operate on the same byte stream.
Returns True for success, False for failure.
GetAdaptersAddresses
Populates json with information about local network adapters, including IPv4 addresses, IPv6 addresses, and MAC addresses. Existing contents of the destination JSON object are replaced or populated according to the returned structure.
Returns True for success, False for failure.
GetLastJsonData
Copies additional JSON details from the most recently called method into json, when that method produced such information. Many methods produce an empty result.
GetMyServerCert
Copies the TLS server certificate configured by InitSslServer into cert. This method is intended for a socket acting as a TLS server and returns False when no server certificate has been configured.
Returns True for success, False for failure.
topGetRcvdClientCert
Copies the client certificate at zero-based index into cert from the TLS handshake of an accepted server-side connection. Use NumReceivedClientCerts to determine the valid index range.
Client certificates are normally supplied only when the server requests mutual TLS authentication. The application can inspect the returned certificate and close the connection when it does not satisfy authorization requirements.
AcceptNext, not on the listener socket.Returns True for success, False for failure.
topGetServerCert
Copies the certificate presented by the remote TLS server into cert for the current client-side TLS connection. The method returns False when the socket is not connected, is not using TLS, or no server certificate is available.
RequireSslCertVerify and/or TlsPinSet when validation is required.Returns True for success, False for failure.
topGetSslAcceptableClientCaDn
Returns the certificate-authority distinguished name at zero-based index from the list sent by a TLS server when it requests a client certificate. Valid indexes range from 0 through NumSslAcceptableClientCAs - 1.
Returns None on failure
InitSslServer
Configures this object to accept TLS connections using cert as the server certificate. Call it before AcceptNext. The certificate must have access to its corresponding private key.
As a convenience, this method sets the Ssl property to True when the object is not already connected.
Returns True for success, False for failure.
LoadTaskCaller
Loads this object with the state of the object that initiated the asynchronous operation represented by task. This is useful when the task has completed on a worker thread and the caller state must be recovered into another wrapper object.
Socket asynchronous method and call this after completion.Returns True for success, False for failure.
topLoadTaskResult
Loads this socket object with the result state produced by a completed asynchronous task whose result is a socket. Call it only after the task has completed successfully.
LastErrorText when loading fails.Returns True for success, False for failure.
topPollDataAvailable
Performs a nonblocking check for readable activity on the socket. It returns True when data or another read-ready condition is present and False when nothing is immediately available.
PollDataAvailableAsync (1)
Creates an asynchronous task to call the PollDataAvailable method with the arguments provided.
Returns None on failure
ReceiveBd
Receives as many bytes as are currently available and appends them to binData. If no data is immediately available, the method waits up to MaxReadIdleMs for the first data.
Returns True for success, False for failure.
topReceiveBdAsync (1)
Creates an asynchronous task to call the ReceiveBd method with the arguments provided.
Returns None on failure
ReceiveBdN
Reads exactly numBytes bytes and appends them to binData. The method continues until the requested count is satisfied or a receive failure occurs. Inactivity is controlled by MaxReadIdleMs.
Returns True for success, False for failure.
ReceiveBdNAsync (1)
Creates an asynchronous task to call the ReceiveBdN method with the arguments provided.
Returns None on failure
ReceiveByte
Reads one byte from the connection and stores its numeric value in ReceivedInt. If bUnsigned is True, the result is in the range 0 through 255; otherwise it is interpreted as a signed byte in the range -128 through 127.
The method waits according to MaxReadIdleMs and returns False on timeout, closure, or another receive failure.
Returns True for success, False for failure.
ReceiveByteAsync (1)
Creates an asynchronous task to call the ReceiveByte method with the arguments provided.
Returns None on failure
ReceiveBytes
Receives and returns as many bytes as are currently available. If no data is immediately available, the method waits for the first data up to MaxReadIdleMs, then returns the available bytes without waiting for a protocol-defined message length.
Returns None on failure
ReceiveBytesAsync (1)
Creates an asynchronous task to call the ReceiveBytes method with the arguments provided.
Returns None on failure
ReceiveBytesENC
Performs the same receive operation as ReceiveBytes, then returns the received bytes encoded using encodingAlg. Supported Chilkat encoding names include base64, modBase64, base32, uu, qp, url, hex, q, b, url_oauth, url_rfc1738, url_rfc2396, and url_rfc3986.
Returns None on failure
ReceiveBytesENCAsync (1)
Creates an asynchronous task to call the ReceiveBytesENC method with the arguments provided.
Returns None on failure
ReceiveBytesN
Reads exactly numBytes bytes and returns them. The method continues reading until the requested count is satisfied or a receive failure occurs. Inactivity is limited by MaxReadIdleMs.
Returns None on failure
ReceiveBytesNAsync (1)
Creates an asynchronous task to call the ReceiveBytesN method with the arguments provided.
Returns None on failure
ReceiveBytesToFile
Receives as many bytes as are currently available and appends them to appendFilename. If no data is immediately available, it waits up to MaxReadIdleMs for the first data.
Returns True for success, False for failure.
topReceiveBytesToFileAsync (1)
Creates an asynchronous task to call the ReceiveBytesToFile method with the arguments provided.
Returns None on failure
ReceiveCount
Reads a four-byte signed integer and returns it. Byte order is controlled by BigEndian, whose default is True for network byte order. The method returns -1 on failure.
-1 is also a valid signed 32-bit value, check LastMethodFailed or ReceiveFailReason when the return value is -1.ReceiveCountAsync (1)
Creates an asynchronous task to call the ReceiveCount method with the arguments provided.
Returns None on failure
ReceiveInt16
Reads a two-byte integer and stores it in ReceivedInt. Set bigEndian to True for network byte order or False for little-endian order. Set bUnsigned to True for a value from 0 through 65535; otherwise the result ranges from -32768 through 32767.
Returns True for success, False for failure.
ReceiveInt16Async (1)
Creates an asynchronous task to call the ReceiveInt16 method with the arguments provided.
Returns None on failure
ReceiveInt32
Reads a four-byte signed integer and stores it in ReceivedInt. Set bigEndian to True for network byte order or False for little-endian order.
Returns True for success, False for failure.
ReceiveInt32Async (1)
Creates an asynchronous task to call the ReceiveInt32 method with the arguments provided.
Returns None on failure
ReceiveNBytesENC
Reads exactly numBytes bytes, then returns them encoded using encodingAlg. Supported encoding names include base64, modBase64, base32, uu, qp, url, hex, q, b, url_oauth, url_rfc1738, url_rfc2396, and url_rfc3986.
The method waits until the requested byte count is received or a receive failure occurs. Inactivity is controlled by MaxReadIdleMs.
Returns None on failure
ReceiveNBytesENCAsync (1)
Creates an asynchronous task to call the ReceiveNBytesENC method with the arguments provided.
Returns None on failure
ReceiveSb
Receives as many bytes as are currently available, decodes them using StringCharset, and appends the resulting text to sb. If no data is immediately available, the method waits up to MaxReadIdleMs.
Returns True for success, False for failure.
topReceiveSbAsync (1)
Creates an asynchronous task to call the ReceiveSb method with the arguments provided.
Returns None on failure
ReceiveString
Receives as many bytes as are currently available and decodes them using StringCharset. If no data is immediately available, the method waits up to MaxReadIdleMs for the first data.
Returns None on failure
ReceiveStringAsync (1)
Creates an asynchronous task to call the ReceiveString method with the arguments provided.
Returns None on failure
ReceiveStringMaxN
Receives and decodes text like ReceiveString, but returns at most maxByteCount input bytes. The limit is measured in bytes, not Unicode characters.
Returns None on failure
ReceiveStringMaxNAsync (1)
Creates an asynchronous task to call the ReceiveStringMaxN method with the arguments provided.
Returns None on failure
ReceiveStringUntilByte
Reads until the byte value lookForByte is encountered. The returned string contains the preceding bytes but excludes the matching byte. Incoming bytes are decoded according to StringCharset.
Returns None on failure
ReceiveStringUntilByteAsync (1)
Creates an asynchronous task to call the ReceiveStringUntilByte method with the arguments provided.
Returns None on failure
ReceiveToCRLF
Reads and decodes text until the byte sequence CRLF (\r\n) is received. The returned string includes the terminating CRLF. Incoming bytes are decoded using StringCharset.
Returns None on failure
ReceiveToCRLFAsync (1)
Creates an asynchronous task to call the ReceiveToCRLF method with the arguments provided.
Returns None on failure
ReceiveUntilByte
Reads bytes until lookForByte is encountered and returns all bytes up to and including that byte. The argument must identify a one-byte value from 0 through 255.
Returns None on failure
ReceiveUntilByteAsync (1)
Creates an asynchronous task to call the ReceiveUntilByte method with the arguments provided.
Returns None on failure
ReceiveUntilByteBd
Reads bytes until lookForByte is encountered and appends all bytes up to and including the match to bd. The delimiter must be a one-byte value from 0 through 255.
Returns True for success, False for failure.
topReceiveUntilByteBdAsync (1)
Creates an asynchronous task to call the ReceiveUntilByteBd method with the arguments provided.
Returns None on failure
ReceiveUntilMatch
Reads and decodes text until matchStr is found. The returned string includes the matching text. Incoming bytes are decoded according to StringCharset.
For example, a protocol header terminated by a blank line can be read using \r\n\r\n. If no additional data arrives for longer than MaxReadIdleMs, the method fails and ReceiveFailReason is typically 5.
ReceivedCount can increase by more than the length returned.Returns None on failure
ReceiveUntilMatchAsync (1)
Creates an asynchronous task to call the ReceiveUntilMatch method with the arguments provided.
Returns None on failure
ReceiveUntilMatchSb
Reads and decodes text until matchStr is found, then appends the received text, including the match, to sb. Text decoding uses StringCharset, and inactivity is controlled by MaxReadIdleMs.
Returns True for success, False for failure.
topReceiveUntilMatchSbAsync (1)
Creates an asynchronous task to call the ReceiveUntilMatchSb method with the arguments provided.
Returns None on failure
ResetPerf
Restarts one direction of transfer-rate measurement. Set rcvPerf to True to reset receive measurement for RcvBytesPerSec; set it to False to reset send measurement for SendBytesPerSec.
SelectForReading
Waits up to timeoutMs for read-ready activity on this socket or, when the caller is a socket set, on any contained socket. Use 0 to poll.
| Return value | Meaning |
|---|---|
| Positive | The number of sockets in the read-ready set. |
| 0 | No socket became ready before the timeout. |
| -1 | An error occurred. |
A connected socket is read-ready when data is available or when a close/error condition can be detected. A listener is read-ready when an incoming connection is pending. Use the selector properties to choose a ready socket from a set.
SelectForReadingAsync (1)
Creates an asynchronous task to call the SelectForReading method with the arguments provided.
Returns None on failure
SelectForWriting
Waits up to timeoutMs for this socket, or sockets in a socket set, to become writable without blocking. Use 0 to poll.
| Return value | Meaning |
|---|---|
| Positive | The number of sockets in the write-ready set. |
| 0 | No socket became writable before the timeout. |
| -1 | An error occurred. |
SelectForWritingAsync (1)
Creates an asynchronous task to call the SelectForWriting method with the arguments provided.
Returns None on failure
SendBd
Sends bytes from binData, beginning at offset. If numBytes is greater than 0, exactly that many bytes are sent; if it is 0, bytes are sent from offset through the end. When both values are 0, the entire BinData is sent.
The method is synchronous and uses MaxSendIdleMs as the send-progress inactivity limit.
BinData. No application message framing is added.Returns True for success, False for failure.
SendBdAsync (1)
Creates an asynchronous task to call the SendBd method with the arguments provided.
Returns None on failure
SendByte
Sends one byte whose value is specified by value. The value must be in the range 0 through 255. The method returns after the byte has been accepted for transmission or a send failure occurs.
Returns True for success, False for failure.
SendByteAsync (1)
Creates an asynchronous task to call the SendByte method with the arguments provided.
Returns None on failure
SendBytes
Sends all bytes in data over the connected TCP or TLS socket. The method is synchronous and returns after the bytes have been accepted for transmission. A lack of send progress for longer than MaxSendIdleMs causes failure.
Returns True for success, False for failure.
SendBytesAsync (1)
Creates an asynchronous task to call the SendBytes method with the arguments provided.
Returns None on failure
SendBytesENC
Decodes encodedBytes using encodingAlg, then sends the resulting binary bytes. Supported Chilkat encoding names include base64, modBase64, base32, base58, uu, qp, url, hex, q, b, url_oauth, url_rfc1738, url_rfc2396, and url_rfc3986.
For example, encodedBytes="00010203040506" with encodingAlg="hex" sends seven bytes with values 00 through 06.
SendFailReason and LastErrorText.SendBytesENCAsync (1)
Creates an asynchronous task to call the SendBytesENC method with the arguments provided.
Returns None on failure
SendCount
Sends byteCount as a four-byte signed integer. Byte order is controlled by BigEndian, whose default is True for network byte order. The peer can read the value using ReceiveCount.
Returns True for success, False for failure.
topSendCountAsync (1)
Creates an asynchronous task to call the SendCount method with the arguments provided.
Returns None on failure
SendInt16
Sends value as a two-byte integer. Set bigEndian to True for network byte order or False for little-endian order. Values outside the representable 16-bit range should not be used.
Returns True for success, False for failure.
SendInt16Async (1)
Creates an asynchronous task to call the SendInt16 method with the arguments provided.
Returns None on failure
SendInt32
Sends value as a four-byte integer. Set bigEndian to True for network byte order or False for little-endian order.
Returns True for success, False for failure.
topSendInt32Async (1)
Creates an asynchronous task to call the SendInt32 method with the arguments provided.
Returns None on failure
SendSb
Encodes the contents of sb using StringCharset and sends the resulting bytes. The method is synchronous and uses MaxSendIdleMs as the send-progress inactivity limit.
StringBuilder content.Returns True for success, False for failure.
topSendSbAsync (1)
Creates an asynchronous task to call the SendSb method with the arguments provided.
Returns None on failure
SendString
Encodes stringToSend using StringCharset and sends the resulting bytes over the connected TCP or TLS socket. The synchronous method returns after the bytes have been accepted for transmission or a send failure occurs. Send inactivity is limited by MaxSendIdleMs.
Returns True for success, False for failure.
SendStringAsync (1)
Creates an asynchronous task to call the SendString method with the arguments provided.
Returns None on failure
SendWakeOnLan
Sends a Wake-on-LAN magic packet for macAddress to the UDP broadcast address ipBroadcastAddr and port. The MAC address is six bytes written as hexadecimal, for example 000102030405. Ports 7 and 9 are commonly used.
Call this method without first calling Connect. The target computer must have Wake-on-LAN enabled in firmware, the network adapter, and the operating system, and the network must permit the broadcast packet.
Returns True for success, False for failure.
SendWakeOnLan2
Sends the same Wake-on-LAN magic packet as SendWakeOnLan and appends a SecureOn password. password is a hexadecimal string representing four or six bytes.
Returns True for success, False for failure.
topSetSslClientCert
Configures cert as the client certificate for subsequent TLS connections. The certificate must have access to its private key. Use this only when the server requests or requires client-certificate authentication.
Connect or ConvertToSsl. A certificate without its private key cannot prove client identity.Returns True for success, False for failure.
SetSslClientCertPem
Loads and configures a TLS client certificate and private key from PEM data or a PEM filename supplied in pemDataOrFilename. Use pemPassword when the private key is encrypted.
Returns True for success, False for failure.
topSetSslClientCertPfx
Loads and configures a TLS client certificate and private key from the PFX/P12 file pfxFilename, using pfxPassword. Use this only when the server requests or requires client-certificate authentication.
Returns True for success, False for failure.
SleepMs
Pauses the calling thread for approximately millisec milliseconds. This is a convenience method and does not perform network I/O or keep a connection alive.
SshAuthenticatePk
Authenticates the SSH tunnel session as sshLogin using privateKey. Call SshOpenTunnel first. The SSH server must have the corresponding public key authorized for that account.
Returns True for success, False for failure.
topSshAuthenticatePkAsync (1)
Creates an asynchronous task to call the SshAuthenticatePk method with the arguments provided.
Returns None on failure
SshAuthenticatePw
Authenticates the SSH tunnel session using sshLogin and sshPassword. Call SshOpenTunnel first and authenticate before opening forwarded channels.
Returns True for success, False for failure.
topSshAuthenticatePwAsync (1)
Creates an asynchronous task to call the SshAuthenticatePw method with the arguments provided.
Returns None on failure
SshCloseTunnel
Closes the SSH tunnel opened by SshOpenTunnel and terminates its forwarded channels. It does not close unrelated SSH objects or connections.
Returns True for success, False for failure.
topSshCloseTunnelAsync (1)
Creates an asynchronous task to call the SshCloseTunnel method with the arguments provided.
Returns None on failure
SshNewChannel
Opens a new port-forwarded channel through the authenticated SSH tunnel to hostname:port and populates channel with the connected socket. If ssl is True, Chilkat establishes TLS to the destination inside the SSH tunnel. maxWaitMs limits destination connection establishment.
Multiple channels can share one authenticated SSH tunnel and can target different destination host/port pairs.
SshOpenTunnel and authenticate successfully before opening channels.Returns True for success, False for failure.
topSshNewChannelAsync (1)
Creates an asynchronous task to call the SshNewChannel method with the arguments provided.
Returns None on failure
SshOpenTunnel
Connects to the SSH server at sshHostname:sshPort and initializes an SSH tunneling session. Port 22 is conventional but not required.
After this succeeds, authenticate with SshAuthenticatePw or SshAuthenticatePk, then open forwarded destination channels with SshNewChannel. Multiple channels can share the same authenticated tunnel.
MaxReadIdleMs.Returns True for success, False for failure.
SshOpenTunnelAsync (1)
Creates an asynchronous task to call the SshOpenTunnel method with the arguments provided.
Returns None on failure
StartTiming
Starts or restarts the object's convenience timer. Read ElapsedSeconds to obtain the whole number of seconds since this call.
TakeConnection
Transfers the active connection from sock to this object. If this object already owns a connection, that connection is closed first. Unlike TakeSocket, this method does not create a socket set.
Returns True for success, False for failure.
topTakeSocket
Transfers ownership of sock into this object's internal socket set. After one or more successful calls, the caller acts as a collection of connected and/or listener sockets.
Use SelectorIndex to route normal methods and properties to a contained socket. Use SelectForReading and SelectForWriting with the selector-result properties to wait on the set.
Returns True for success, False for failure.
TlsRenegotiate
Requests TLS renegotiation on an established TLS connection, causing another handshake to negotiate new security parameters where the protocol and peer support it.
Returns True for success, False for failure.
topTlsRenegotiateAsync (1)
Creates an asynchronous task to call the TlsRenegotiate method with the arguments provided.
Returns None on failure
UseSsh
Configures this socket to route subsequent Connect calls through the already connected and authenticated Ssh object. The destination host and port passed to Connect are reached by SSH port forwarding rather than by a direct TCP connection.
This is one of several SSH-tunneling models in Chilkat. Alternatives include this class's SshOpenTunnel/SshNewChannel workflow and the separate SshTunnel class for background static or dynamic forwarding.
Ssh object must remain connected and authenticated while the forwarded socket connection is being established and used.Returns True for success, False for failure.
Deprecated
AcceptNextConnection
AcceptNext instead.Waits for and accepts the next incoming connection on a listening socket. maxWaitMs is the maximum time to wait for an incoming TCP connection; use 0 to wait indefinitely. On success, a new Socket object is returned.
MaxReadIdleMs and MaxSendIdleMs. Leaving those values at 0 permits an unresponsive client to keep the handshake waiting indefinitely.Returns None on failure
AcceptNextConnectionAsync (1) (2)
Creates an asynchronous task to call the AcceptNextConnection method with the arguments provided.
Returns None on failure
CloneSocket
DupSocket instead.Returns another Socket object that shares the same underlying TCP or TLS connection. Reads and writes made through either object operate on the same byte stream.
Returns None on failure
GetMyCert
GetMyServerCert instead.Returns the certificate configured for this object when it is acting as a TLS server. The certificate is initially supplied to InitSslServer.
Returns None on failure
GetReceivedClientCert
GetRcvdClientCert instead.Returns the client certificate at the zero-based index received during the TLS handshake on an accepted server-side connection. Use NumReceivedClientCerts to determine the valid range.
AcceptNextConnection, not on the listener. The server application remains responsible for deciding whether the certificate authorizes the client.Returns None on failure
GetSslServerCert
GetServerCert instead.Returns the certificate presented by the remote TLS server for the current client-side TLS connection. It returns a null reference when the socket is not connected or the connection is not using TLS.
Returns None on failure
LastJsonData
GetLastJsonData instead.Returns a JSON object containing additional details produced by the most recently called method when such details are available.
Returns None on failure
SshOpenChannel
SshNewChannel instead.Opens a port-forwarded channel through the authenticated SSH tunnel to hostname:port. If ssl is True, Chilkat performs TLS to the destination inside the SSH tunnel. maxWaitMs limits destination connection establishment.
Returns None on failure
SshOpenChannelAsync (1) (2)
Creates an asynchronous task to call the SshOpenChannel method with the arguments provided.
Returns None on failure