Socket Swift Reference Documentation

CkoSocket

Current Version: 11.5.0

Chilkat.Socket

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

Connect to remote hosts and ports for custom protocols or direct socket-level communication.

TLS and certificates

Use SSL/TLS, inspect certificates, provide client certificates, and control TLS-related behavior when secure sockets are required.

Send and receive data

Send and receive strings, byte data, files, fixed-size blocks, delimiter-terminated messages, or protocol-specific data patterns.

Server-side sockets

Listen for and accept incoming client connections when implementing simple socket servers or custom listener workflows.

Proxy and SSH tunneling

Route socket connections through HTTP proxies, SOCKS proxies, or SSH-tunneled connections when network topology requires it.

Timeouts and diagnostics

Configure connection and read/write timeouts, monitor counters, and use logs and LastErrorText to diagnose connection or protocol failures.

Common pattern: Use 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

let obj = CkoSocket()!

Properties

AbortCurrent
abortCurrent: Bool
Introduced in version 9.5.0.58

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.

Note: A synchronous call can be cancelled from another thread by setting this property on the same object. The method returns its normal failure value, and LastErrorText describes the abort.

top
AcceptFailReason
acceptFailReason: Int (read-only)
Introduced in version 9.5.0.50

Contains a numeric reason code when AcceptNext or the deprecated AcceptNextConnection method fails. Examine this property immediately after the failed accept operation.

CodeMeaning
0Success.
1An asynchronous accept operation is already in progress.
3Internal failure, such as an allocation failure.
5No incoming connection was accepted before the wait interval expired.
6The operation was aborted by the application.
9An unspecified fatal socket error occurred.
20The socket has not first been bound and placed into listening mode.
99The Chilkat component is not unlocked.
100TLS internal error.
102Unexpected TLS handshake message.
109Failed to read TLS handshake messages.
114Failed to send the ChangeCipherSpec message.
115Failed to send the Finished message.
116The client's Finished message was invalid.
117Unable to agree on a TLS protocol version.
118Unable to agree on a cipher suite.
119Failed to read the client's ClientHello message.
120Failed to send TLS handshake messages.
121Failed to process the client certificate message.
122Failed to process the client certificate URL message.
123Failed to process the client key-exchange message.
124Failed to process the CertificateVerify message.
125An SSL 2.0 connection attempt was received and rejected.
Note: When the listener requires TLS, accepting a connection includes the server-side TLS handshake. A TLS-related failure may therefore also be reflected by the send and receive failure state.

top
AlpnProtocol
alpnProtocol: String!
Introduced in version 9.5.0.82

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.

Note: ALPN negotiation does not implement the selected application protocol. The application must still speak that protocol over the established TLS connection.

top
BandwidthThrottleDown
bandwidthThrottleDown: Int
Introduced in version 9.5.0.49

Limits receive throughput to approximately the specified number of bytes per second. The default value is 0, which disables receive throttling.

Note: The limit is approximate and is applied over time; it does not define socket packet sizes or message boundaries.

top
BandwidthThrottleUp
bandwidthThrottleUp: Int
Introduced in version 9.5.0.49

Limits send throughput to approximately the specified number of bytes per second. The default value is 0, which disables send throttling.

Note: The limit is approximate and is applied over time; it does not define socket packet sizes or message boundaries.

More Information and Examples
top
BigEndian
bigEndian: Bool

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.

Note: This property applies only to the four-byte count methods. The SendInt16, SendInt32, ReceiveInt16, and ReceiveInt32 methods receive their byte-order choice as an argument.

top
ClientIpAddress
clientIpAddress: String!

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.

Important: Supply a local numeric IPv4 or IPv6 address that belongs to the computer. Do not supply a DNS hostname or a remote address. The address family must be compatible with the destination connection.

More Information and Examples
top
ClientPort
clientPort: Int

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.

Important: Setting a fixed client port is unusual and can cause connection failures when the port is already in use or unavailable. Use a nonzero value only when the remote system or network policy explicitly requires a particular source port.

top
ConnectFailReason
connectFailReason: Int (read-only)

Contains a numeric reason code when Connect fails. Examine this property immediately after the failed connection attempt.

CodeMeaning
0Success.
1The hostname is empty.
2DNS lookup failed.
3DNS lookup timed out.
4The operation was aborted by the application.
5Internal failure.
6The TCP connection attempt timed out.
7The connection was rejected or otherwise could not be established.
100TLS internal error.
101Failed to send ClientHello.
102Unexpected TLS handshake message.
103Failed to read ServerHello.
104The server did not provide a certificate.
105Unexpected TLS protocol version.
106Server-certificate verification failed.
107The negotiated TLS protocol version was not permitted.
108An application-defined server-certificate requirement failed.
109Failed to read TLS handshake messages.
110Failed to send the client-certificate message.
111Failed to send the client key-exchange message.
112The client certificate's private key was not accessible.
113Failed to send the client CertificateVerify message.
114Failed to send the ChangeCipherSpec message.
115Failed to send the Finished message.
116The server's Finished message was invalid.
Note: The TCP connection timeout supplied to Connect is distinct from DNS, proxy, and TLS-handshake inactivity limits. See MaxReadIdleMs and MaxSendIdleMs.

top
DebugLogFilePath
debugLogFilePath: String!

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.

More Information and Examples
top
ElapsedSeconds
elapsedSeconds: Int (read-only)

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.

Note: This convenience timer is associated with the object; it is not a network timeout and does not affect socket operations.

top
HeartbeatMs
heartbeatMs: Int

Specifies the interval, in milliseconds, between AbortCheck callbacks during supported long-running operations. The default is 0, which disables periodic AbortCheck callbacks.

Note: This setting does not send network heartbeat packets and does not implement TCP keepalive. It only controls application callbacks that provide an opportunity to cancel an operation.

More Information and Examples
top
HttpProxyAuthMethod
httpProxyAuthMethod: String!

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.

Important: Basic proxy credentials are only encoded, not encrypted. Protect them by using an appropriate secure network path to the proxy.

top
HttpProxyDomain
httpProxyDomain: String!

Specifies the optional Windows domain used for NTLM authentication to an HTTP proxy. It is ignored unless HttpProxyAuthMethod is NTLM.

top
HttpProxyForHttp
httpProxyForHttp: Bool
Introduced in version 9.5.0.70

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.

Important: Set this before connecting through the HTTP proxy. An incorrect value can produce a connection that is established using the wrong proxy mode for the application protocol.

More Information and Examples
top
HttpProxyHostname
httpProxyHostname: String!

Specifies the hostname or numeric IP address of the HTTP proxy. Leave it empty to connect directly without an HTTP proxy.

top
HttpProxyPassword
httpProxyPassword: String!

Specifies the password used to authenticate with the HTTP proxy. It is used together with HttpProxyUsername and the selected HttpProxyAuthMethod.

Important: Do not write proxy passwords to logs or expose them in diagnostic output.

top
HttpProxyPort
httpProxyPort: Int

Specifies the TCP port of the HTTP proxy. Common values include 8080 and 3128, but the correct port is determined by the proxy configuration.

top
HttpProxyUsername
httpProxyUsername: String!

Specifies the username used to authenticate with the HTTP proxy. It is ignored when the proxy does not require authentication.

top
IsConnected
isConnected: Bool (read-only)

Returns true when the socket is in its last known connected state; otherwise returns false. Explicitly closing the socket updates this property immediately.

Important: TCP does not continuously notify an idle application that a peer or network path has disappeared. This property can remain 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.

top
KeepAlive
keepAlive: Bool
Introduced in version 9.5.0.49

Controls the operating system SO_KEEPALIVE option for the underlying TCP socket. The default is true.

Note: TCP keepalive is distinct from an application-protocol heartbeat. The operating system controls the keepalive timing and retry policy unless configured by platform-specific means.

top
KeepSessionLog
keepSessionLog: Bool

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.

Important: Session logs can contain credentials, tokens, private application data, or decrypted TLS payloads. Enable logging only for diagnostics and protect or remove the resulting data.

More Information and Examples
top
LastErrorHtml
lastErrorHtml: String! (read-only)

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.

top
LastErrorText
lastErrorText: String! (read-only)

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.

top
LastErrorXml
lastErrorXml: String! (read-only)

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.

top
LastMethodFailed
lastMethodFailed: Bool (read-only)

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.

Note: Read this property immediately after the method of interest. Calling another method can replace the stored result state.

top
LastMethodSuccess
lastMethodSuccess: Bool

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.

top
ListenIpv6
listenIpv6: Bool

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.

Note: On systems that support dual-stack sockets, an IPv6 listener may also accept IPv4 connections. Exact dual-stack behavior is operating-system dependent.

top
ListenPort
listenPort: Int (read-only)
Introduced in version 9.5.0.59

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.

top
LocalIpAddress
localIpAddress: String! (read-only)

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.

top
LocalPort
localPort: Int (read-only)

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.

top
MaxReadIdleMs
maxReadIdleMs: Int

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.

Important: This is an inactivity timeout, not necessarily a limit on the total duration of the operation. A slow peer can keep an operation active by continuing to make progress.

top
MaxSendIdleMs
maxSendIdleMs: Int

Specifies the maximum number of milliseconds a send-related operation may remain without making additional write progress. The default is 0, which waits indefinitely.

Important: This is an inactivity timeout, not necessarily a limit on the total duration of a large send.

top
MyIpAddress
myIpAddress: String! (read-only)

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.

Note: This is normally a private or internal address and is not a reliable way to discover a public Internet address behind NAT. For an actual bound or connected socket, use LocalIpAddress and LocalPort.

More Information and Examples
top
NumBytesAvailable
numBytesAvailable: Int (read-only)
Introduced in version 9.5.0.94

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.

Important: Do not use this value as a message length. TCP is a byte stream, and a complete application message can arrive in multiple reads or multiple messages can be available together.

top
NumReceivedClientCerts
numReceivedClientCerts: Int (read-only)

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.

Important: Read this property on the accepted connection object populated by AcceptNext, not on the listener socket. Client certificates are normally present only when the server requested mutual TLS authentication.

top
NumSocketsInSet
numSocketsInSet: Int (read-only)

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.

More Information and Examples
top
NumSslAcceptableClientCAs
numSslAcceptableClientCAs: Int (read-only)

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.

Note: The list is guidance from the server for selecting a client certificate. It does not itself authenticate the server or guarantee that a particular client certificate will be accepted.

top
ObjectId
objectId: Int (read-only)

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.

Note: The value is for runtime correlation only and should not be persisted as a durable identifier.

top
PercentDoneScale
percentDoneScale: Int
Introduced in version 9.5.0.49

Defines the numeric value that represents 100 percent in PercentDone callbacks. The default is 100. For example, a scale of 1000 permits tenths-of-a-percent values, so 453 represents 45.3 percent.

Values are clamped to the range 10 through 100000. The property affects only operations whose progress can be measured and only language bindings that expose callbacks.

top
PreferIpv6
preferIpv6: Bool

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.

Note: A preference does not guarantee that the chosen address family will be usable. Connection success still depends on local routing, DNS results, firewall policy, and server availability.

top
RcvBytesPerSec
rcvBytesPerSec: Int (read-only)
Introduced in version 9.5.0.78

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.

top
ReceivedCount
receivedCount: Int

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.

Note: Use RcvBytesPerSec when measuring raw transfer rate including protocol overhead.

top
ReceivedInt
receivedInt: Int
Introduced in version 9.5.0.50

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.

top
ReceiveFailReason
receiveFailReason: Int (read-only)
Introduced in version 9.5.0.49

Contains a numeric reason code when a receive method fails. Examine it immediately after the failed receive operation.

CodeMeaning
0Success.
1An asynchronous receive operation is already in progress.
2The socket is not connected.
3Internal failure, such as an allocation failure.
4Invalid parameters were supplied.
5No additional data arrived within MaxReadIdleMs.
6The operation was aborted by the application.
7The peer reset the connection.
8The host operating system aborted the established connection.
9An unspecified fatal socket error occurred.
10The peer closed the connection.

top
ReceivePacketSize
receivePacketSize: Int

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.

Note: TCP is a byte stream. This value is an internal buffering choice and does not correspond to application messages, peer send calls, IP packets, or TLS records.

top
RemoteIpAddress
remoteIpAddress: String! (read-only)

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.

top
RemotePort
remotePort: Int (read-only)

Returns the TCP port of the connected peer.

top
RequireSslCertVerify
requireSslCertVerify: Bool

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.

Important: Certificate verification and public-key pinning serve different purposes. Use TlsPinSet when the application also requires an exact SPKI pin match.

top
SelectorIndex
selectorIndex: Int

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.

Note: After SelectForReading or SelectForWriting, copy the desired ready index from SelectorReadIndex or SelectorWriteIndex into this property before reading or writing.

More Information and Examples
top
SelectorReadIndex
selectorReadIndex: Int

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.

Note: A read-ready socket can have data available, a pending incoming connection when it is a listener, or a close/error condition. Perform the appropriate accept or receive operation to determine which occurred.

More Information and Examples
top
SelectorWriteIndex
selectorWriteIndex: Int

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.

top
SendBytesPerSec
sendBytesPerSec: Int (read-only)
Introduced in version 9.5.0.78

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.

top
SendFailReason
sendFailReason: Int (read-only)
Introduced in version 9.5.0.49

Contains a numeric reason code when a send method fails. Examine it immediately after the failed send operation.

CodeMeaning
0Success.
1An asynchronous send operation is already in progress.
2The socket is not connected.
3Internal failure, such as an allocation failure.
4Invalid parameters were supplied.
5The socket remained unable to make send progress for longer than MaxSendIdleMs.
6The operation was aborted by the application.
7The peer reset the connection.
8The host operating system aborted the established connection.
9An unspecified fatal socket error occurred.
10The peer closed the connection.
11Text or encoded input could not be converted or decoded, such as an invalid StringCharset conversion or malformed encoded data.

top
SendPacketSize
sendPacketSize: Int

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.

Note: This value does not preserve message boundaries and does not determine IP packet sizes. TCP remains a continuous byte stream.

top
SessionLog
sessionLog: String! (read-only)

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.

Important: The log can contain sensitive plaintext even when the network connection uses TLS. Treat it as diagnostic data and protect it accordingly.

More Information and Examples
top
SessionLogEncoding
sessionLogEncoding: String!

Controls how bytes are rendered in SessionLog. The default is esc.

ValueFormat
escCompact C-style escaped text. Printable ASCII remains readable; control and nonprintable bytes are escaped, such as \r, \n, and \xHH.
hexEvery byte is represented in hexadecimal, which is larger but unambiguous for binary protocols.

More Information and Examples
top
SniHostname
sniHostname: String!
Introduced in version 9.5.0.82

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.

Note: SNI changes only the TLS handshake name. It does not change the TCP destination, DNS lookup, or any application-protocol host field.

top
SocksHostname
socksHostname: String!

Specifies the hostname or numeric IP address of the SOCKS proxy. It is used only when SocksVersion is 4 or 5.

top
SocksPassword
socksPassword: String!

Specifies the password for SOCKS5 username/password authentication. SOCKS4 does not define a password field, so this property is ignored for SOCKS4.

Important: SOCKS5 username/password authentication does not itself encrypt credentials. Security depends on the network path to the proxy.

top
SocksPort
socksPort: Int

Specifies the TCP port of the SOCKS proxy. The default is 1080. It is used only when SocksVersion is 4 or 5.

top
SocksUsername
socksUsername: String!

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.

top
SocksVersion
socksVersion: Int

Selects whether connections are routed through a SOCKS proxy.

ValueBehavior
0Do not use a SOCKS proxy. This is the default.
4Connect through a SOCKS4 proxy.
5Connect through a SOCKS5 proxy.

top
SoRcvBuf
soRcvBuf: Int

Requests the operating-system receive-buffer size for the TCP socket. The default requested value is 4194304 bytes. Most applications should leave it unchanged.

Note: The operating system may round, clamp, or internally scale the requested value. Increasing the buffer does not by itself guarantee higher throughput; measure performance before changing it.

top
SoReuseAddr
soReuseAddr: Bool

Controls the SO_REUSEADDR option for a socket that will bind and listen. The default is true. Set it before BindAndListen, BindAndListenPortRange, or InitSslServer.

Important: The exact meaning of 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.

top
SoSndBuf
soSndBuf: Int

Requests the operating-system send-buffer size for the TCP socket. The default requested value is 262144 bytes. Most applications should leave it unchanged.

Note: The operating system may round, clamp, or internally scale the value. Test representative workloads before increasing it.

top
Ssl
ssl: Bool

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.

Important: This is a listener requirement, not a connection-state indicator. Use TlsVersion to determine whether the current or most recent connection negotiated TLS. Configure the server certificate with InitSslServer before accepting TLS clients.

top
SslAllowedCiphers
sslAllowedCiphers: String!
Introduced in version 9.5.0.48

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.

Important: The set of implemented suites and the meaning of 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.

top
SslProtocol
sslProtocol: String!

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.

Important: Do not enable SSL 3.0, TLS 1.0, or TLS 1.1 unless compatibility with a legacy peer is unavoidable. Prefer TLS 1.2 or higher or the current default policy.

More Information and Examples
top
StringCharset
stringCharset: String!

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.

Important: TCP transports bytes, not text. Both peers must agree on the encoding and message framing. Use byte-oriented methods when the protocol is binary or when exact byte preservation is required.

top
TcpNoDelay
tcpNoDelay: Bool

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.

Note: Disabling Nagle can improve interactive request/response latency but may increase packet overhead. It is not universally faster for bulk transfers.

top
TlsCipherSuite
tlsCipherSuite: String! (read-only)
Introduced in version 9.5.0.49

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.

top
TlsPinSet
tlsPinSet: String!
Introduced in version 9.5.0.55

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.

Important: Pinning is an additional identity check and is operationally strict. Include backup pins before rotating server keys, or a legitimate certificate renewal can break connectivity.

More Information and Examples
top
TlsVersion
tlsVersion: String! (read-only)
Introduced in version 9.5.0.49

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.

top
UncommonOptions
uncommonOptions: String!
Introduced in version 9.5.0.80

Provides comma-separated compatibility or platform-specific options. The default is the empty string and should normally remain unchanged.

KeywordBehavior
ProtectFromVpnOn Android, attempts to route the socket outside an active VPN.
EnableTls13Historical compatibility option introduced when TLS 1.3 was not yet enabled by default. It is generally unnecessary in current versions.
ListenAllNetworkInterfacesCauses a listener to bind to all IPv4 interfaces (0.0.0.0) instead of loopback (127.0.0.1).
Important: These options are intentionally uncommon and may be platform- or version-specific. Use only when the documented behavior is required.

More Information and Examples
top
UserData
userData: String!

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.

top
VerboseLogging
verboseLogging: Bool

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.

top
Version
version: String! (read-only)

Version of the component/library, such as "10.1.0"

More Information and Examples
top

Methods

AcceptNext
acceptNext(maxWaitMs: Int, socket: CkoSocket) -> Bool
Introduced in version 11.0.0

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.

Important: For a TLS listener, this method also performs the TLS handshake. 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.
Note: Connection-specific properties and received client certificates are available on the accepted socket, not on the listener.

Returns true for success, false for failure.

More Information and Examples
top
AcceptNextAsync (1)
acceptNextAsync(maxWaitMs: Int, socket: CkoSocket) -> CkoTask
Introduced in version 11.0.0

Creates an asynchronous task to call the AcceptNext method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
AddSslAcceptableClientCaDn
addSslAcceptableClientCaDn(certAuthDN: String) -> Bool

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.

Important: This list is only one part of client-certificate authentication. The application should still inspect the certificates received on the accepted socket and apply its authorization policy.

Returns true for success, false for failure.

top
BindAndListen
bindAndListen(port: Int, backlog: Int) -> Bool

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.

Note: The operating system may cap or adjust the requested backlog. Choose a value based on burst arrival rate and how quickly the application returns to accepting connections.

Returns true for success, false for failure.

top
BindAndListenAsync (1)
bindAndListenAsync(port: Int, backlog: Int) -> CkoTask

Creates an asynchronous task to call the BindAndListen method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
BindAndListenPortRange
bindAndListenPortRange(beginPort: Int, endPort: Int, backLog: Int) -> Int
Introduced in version 9.5.0.69

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.

Note: Use AcceptNext after a port is successfully selected.
top
BindAndListenPortRangeAsync (1)
bindAndListenPortRangeAsync(beginPort: Int, endPort: Int, backLog: Int) -> CkoTask
Introduced in version 9.5.0.69

Creates an asynchronous task to call the BindAndListenPortRange method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
BuildHttpGetRequest
buildHttpGetRequest(url: String) -> String
Introduced in version 9.5.0.35

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.

Tip: Use the higher-level Http or Rest class for normal HTTP work. This helper is intended for low-level socket examples or custom HTTP handling.

Returns nil on failure

More Information and Examples
top
CheckWriteable
checkWriteable(maxWaitMs: Int) -> Int

Waits up to maxWaitMs for the connected socket to become writable. Use 0 to poll without waiting.

Return valueMeaning
1The socket is connected and currently writable.
0The wait timed out or the operation was aborted.
-1The socket is not connected or an error occurred.
Note: Writable means the operating system can presently accept more bytes into its send buffer. It does not mean the remote application has received or processed them.
top
CheckWriteableAsync (1)
checkWriteableAsync(maxWaitMs: Int) -> CkoTask

Creates an asynchronous task to call the CheckWriteable method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ClearSessionLog
clearSessionLog()

Clears the accumulated text returned by SessionLog. It does not change KeepSessionLog or close the connection.

top
Close
close(maxWaitMs: Int) -> Bool

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.

Note: After this call, IsConnected is false. A graceful close cannot guarantee that the remote application processed all previously sent data.

Returns true for success, false for failure.

top
CloseAsync (1)
closeAsync(maxWaitMs: Int) -> CkoTask

Creates an asynchronous task to call the Close method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
Connect
connect(hostname: String, port: Int, ssl: Bool, maxWaitMs: Int) -> Bool

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.

Important: A successful TCP connection only establishes a byte stream. It does not authenticate an application protocol unless TLS certificate verification, pinning, or protocol-specific authentication is configured as required.
Note: Idle TCP connections do not automatically close merely because no application data is sent. Whether an idle path remains usable depends on peers, NAT devices, proxies, firewalls, and operating-system TCP keepalive behavior.

Returns true for success, false for failure.

top
ConnectAsync (1)
connectAsync(hostname: String, port: Int, ssl: Bool, maxWaitMs: Int) -> CkoTask

Creates an asynchronous task to call the Connect method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ConvertFromSsl
convertFromSsl() -> Bool

Ends the TLS layer while leaving the underlying TCP connection open for subsequent unencrypted communication. This is the reverse of a STARTTLS-style upgrade.

Important: The peer and application protocol must explicitly support returning to plaintext. Arbitrarily removing TLS from a normal secure protocol will usually break the session and can expose data.

Returns true for success, false for failure.

top
ConvertFromSslAsync (1)
convertFromSslAsync() -> CkoTask

Creates an asynchronous task to call the ConvertFromSsl method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ConvertToSsl
convertToSsl() -> Bool

Upgrades an already connected plain TCP socket to TLS by performing a client-side TLS handshake over the existing connection.

Important: Use this only at the point where the application protocol permits a STARTTLS-style upgrade. Configure TLS policy, SNI, certificate verification, pinning, and any client certificate before calling it.

Returns true for success, false for failure.

top
ConvertToSslAsync (1)
convertToSslAsync() -> CkoTask

Creates an asynchronous task to call the ConvertToSsl method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
DnsCacheClear
dnsCacheClear()
Introduced in version 9.5.0.38

Clears Chilkat's process-wide in-memory DNS cache. Subsequent hostname resolutions perform a new lookup as needed.

Important: The cache is shared by Chilkat objects in the process, so clearing it can affect unrelated connections. Normally the cache should be left intact because Chilkat observes DNS record TTL expiration.
top
DnsLookup
dnsLookup(hostname: String, maxWaitMs: Int) -> String

Resolves hostname and returns a numeric IP address. maxWaitMs is the maximum time to wait; use 0 to wait indefinitely.

Note: A hostname can resolve to multiple IPv4 and IPv6 addresses. The returned value is one selected address, influenced by settings such as PreferIpv6; it is not a complete DNS-record enumeration.

Returns nil on failure

More Information and Examples
top
DnsLookupAsync (1)
dnsLookupAsync(hostname: String, maxWaitMs: Int) -> CkoTask

Creates an asynchronous task to call the DnsLookup method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
DupSocket
dup(dest: CkoSocket) -> Bool
Introduced in version 11.0.0

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.

Important: The duplicate is not an independent connection. Coordinate receive operations and closing carefully; data consumed through one object is no longer available to the other.

Returns true for success, false for failure.

More Information and Examples
top
GetAdaptersAddresses
getAdaptersAddresses(json: CkoJsonObject) -> Bool
Introduced in version 10.1.3

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.

Note: Adapter data is local system configuration. It does not identify the public Internet address seen through NAT.

Returns true for success, false for failure.

More Information and Examples
top
GetLastJsonData
getLastJsonData(json: CkoJsonObject)
Introduced in version 11.0.0

Copies additional JSON details from the most recently called method into json, when that method produced such information. Many methods produce an empty result.

Important: Call this immediately after the operation of interest. Any intervening method call can replace the stored details.
top
GetMyServerCert
getMyServerCert(cert: CkoCert) -> Bool
Introduced in version 11.0.0

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.

top
GetRcvdClientCert
getRcvdClientCert(index: Int, cert: CkoCert) -> Bool
Introduced in version 11.0.0

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.

Important: Call this method on the accepted connection object populated by AcceptNext, not on the listener socket.

Returns true for success, false for failure.

top
GetServerCert
getServerCert(cert: CkoCert) -> Bool
Introduced in version 11.0.0

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.

Note: Retrieving the certificate does not itself establish trust. Use RequireSslCertVerify and/or TlsPinSet when validation is required.

Returns true for success, false for failure.

top
GetSslAcceptableClientCaDn
getSslAcceptableClientCaDn(index: Int) -> String

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 nil on failure

top
InitSslServer
initSslServer(cert: CkoCert) -> Bool

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.

Important: A server certificate identifies the server but does not by itself require client authentication. Configure acceptable client CAs and examine received client certificates when mutual TLS is required.

Returns true for success, false for failure.

More Information and Examples
top
LoadTaskCaller
loadTaskCaller(task: CkoTask) -> Bool
Introduced in version 9.5.0.80

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.

Important: Use a task created by a compatible Socket asynchronous method and call this after completion.

Returns true for success, false for failure.

top
LoadTaskResult
loadTaskResult(task: CkoTask) -> Bool
Introduced in version 9.5.0.52

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.

Important: The task and result type must correspond to a compatible socket operation. Check the task result and LastErrorText when loading fails.

Returns true for success, false for failure.

top
PollDataAvailable
pollDataAvailable() -> Bool

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.

Note: A socket can become read-ready because the peer closed or reset the connection. The next receive operation determines whether bytes are available or the connection ended.
top
PollDataAvailableAsync (1)
pollDataAvailableAsync() -> CkoTask

Creates an asynchronous task to call the PollDataAvailable method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveBd
receiveBd(binData: CkoBinData) -> Bool
Introduced in version 9.5.0.65

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.

Important: TCP does not preserve message boundaries. A receive call can return less or more data than a corresponding peer send call. The application protocol must define framing, such as a length prefix, delimiter, fixed size, or connection close.

Returns true for success, false for failure.

top
ReceiveBdAsync (1)
receiveBdAsync(binData: CkoBinData) -> CkoTask
Introduced in version 9.5.0.65

Creates an asynchronous task to call the ReceiveBd method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveBdN
receiveBdN(numBytes: UInt, binData: CkoBinData) -> Bool
Introduced in version 9.5.0.65

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.

Important: Validate protocol-provided lengths before reading large values. A peer that sends too few bytes without closing can keep the method waiting until the inactivity timeout.

Returns true for success, false for failure.

More Information and Examples
top
ReceiveBdNAsync (1)
receiveBdNAsync(numBytes: UInt, binData: CkoBinData) -> CkoTask
Introduced in version 9.5.0.65

Creates an asynchronous task to call the ReceiveBdN method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveByte
receiveByte(bUnsigned: Bool) -> Bool
Introduced in version 9.5.0.50

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.

More Information and Examples
top
ReceiveByteAsync (1)
receiveByteAsync(bUnsigned: Bool) -> CkoTask
Introduced in version 9.5.0.50

Creates an asynchronous task to call the ReceiveByte method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveBytes
receiveBytes() -> NSData

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.

Important: TCP does not preserve message boundaries. A receive call can return less or more data than a corresponding peer send call. The application protocol must define framing, such as a length prefix, delimiter, fixed size, or connection close.

Returns nil on failure

top
ReceiveBytesAsync (1)
receiveBytesAsync() -> CkoTask

Creates an asynchronous task to call the ReceiveBytes method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveBytesENC
receiveBytesENC(encodingAlg: String) -> String

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.

Note: The encoding affects only the returned representation. The bytes received from the network are not transformed by the peer.

Returns nil on failure

top
ReceiveBytesENCAsync (1)
receiveBytesENCAsync(encodingAlg: String) -> CkoTask

Creates an asynchronous task to call the ReceiveBytesENC method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveBytesN
receiveBytesN(numBytes: UInt) -> NSData

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.

Important: If the peer sends fewer bytes and keeps the connection open, the method waits until the inactivity timeout. Use a protocol-defined length and validate it before allocating or waiting for large amounts of data.

Returns nil on failure

top
ReceiveBytesNAsync (1)
receiveBytesNAsync(numBytes: UInt) -> CkoTask

Creates an asynchronous task to call the ReceiveBytesN method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveBytesToFile
receiveBytes(toFile: String) -> Bool

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.

Important: The file is appended to, not replaced. This method performs one availability-based receive operation; it does not automatically read until the peer closes or until an entire file has arrived.

Returns true for success, false for failure.

top
ReceiveBytesToFileAsync (1)
receiveBytes(toFileAsync: String) -> CkoTask

Creates an asynchronous task to call the ReceiveBytesToFile method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveCount
receiveCount() -> Int

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.

Important: Because -1 is also a valid signed 32-bit value, check LastMethodFailed or ReceiveFailReason when the return value is -1.
top
ReceiveCountAsync (1)
receiveCountAsync() -> CkoTask

Creates an asynchronous task to call the ReceiveCount method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveInt16
receiveInt16(bigEndian: Bool, bUnsigned: Bool) -> Bool
Introduced in version 9.5.0.50

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.

More Information and Examples
top
ReceiveInt16Async (1)
receiveInt16Async(bigEndian: Bool, bUnsigned: Bool) -> CkoTask
Introduced in version 9.5.0.50

Creates an asynchronous task to call the ReceiveInt16 method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveInt32
receiveInt32(bigEndian: Bool) -> Bool
Introduced in version 9.5.0.50

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.

top
ReceiveInt32Async (1)
receiveInt32Async(bigEndian: Bool) -> CkoTask
Introduced in version 9.5.0.50

Creates an asynchronous task to call the ReceiveInt32 method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveNBytesENC
receiveNBytesENC(numBytes: UInt, encodingAlg: String) -> String

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 nil on failure

top
ReceiveNBytesENCAsync (1)
receiveNBytesENCAsync(numBytes: UInt, encodingAlg: String) -> CkoTask

Creates an asynchronous task to call the ReceiveNBytesENC method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveSb
receiveSb(sb: CkoStringBuilder) -> Bool
Introduced in version 9.5.0.65

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.

Important: TCP does not preserve message boundaries. A receive call can return less or more data than a corresponding peer send call. The application protocol must define framing, such as a length prefix, delimiter, fixed size, or connection close.

Returns true for success, false for failure.

top
ReceiveSbAsync (1)
receiveSbAsync(sb: CkoStringBuilder) -> CkoTask
Introduced in version 9.5.0.65

Creates an asynchronous task to call the ReceiveSb method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveString
receiveString() -> String

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.

Important: TCP does not preserve message boundaries. A receive call can return less or more data than a corresponding peer send call. The application protocol must define framing, such as a length prefix, delimiter, fixed size, or connection close.
Important: A receive can end in the middle of a multibyte character or application message. For framed text protocols, prefer a fixed-length or delimiter-based receive method.

Returns nil on failure

top
ReceiveStringAsync (1)
receiveStringAsync() -> CkoTask

Creates an asynchronous task to call the ReceiveString method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveStringMaxN
receiveStringMaxN(maxBytes: Int) -> String

Receives and decodes text like ReceiveString, but returns at most maxByteCount input bytes. The limit is measured in bytes, not Unicode characters.

Important: A byte limit can split a multibyte character or a protocol message. Choose a limit compatible with the encoding and framing used by the peer.

Returns nil on failure

top
ReceiveStringMaxNAsync (1)
receiveStringMaxNAsync(maxBytes: Int) -> CkoTask

Creates an asynchronous task to call the ReceiveStringMaxN method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveStringUntilByte
receiveString(untilByte: Int) -> String

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.

Note: The delimiter is a single byte, not a Unicode character. Use this method only when the delimiter has a stable one-byte representation in the protocol encoding.

Returns nil on failure

top
ReceiveStringUntilByteAsync (1)
receiveString(untilByteAsync: Int) -> CkoTask

Creates an asynchronous task to call the ReceiveStringUntilByte method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveToCRLF
receiveToCRLF() -> String

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.

Tip: This is useful for line-oriented Internet protocols. Do not use it for protocols that permit bare LF, binary data, or a different line terminator.

Returns nil on failure

top
ReceiveToCRLFAsync (1)
receiveToCRLFAsync() -> CkoTask

Creates an asynchronous task to call the ReceiveToCRLF method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveUntilByte
receive(untilByte: Int) -> NSData

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 nil on failure

top
ReceiveUntilByteAsync (1)
receive(untilByteAsync: Int) -> CkoTask

Creates an asynchronous task to call the ReceiveUntilByte method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveUntilByteBd
receive(untilByteBd: Int, bd: CkoBinData) -> Bool
Introduced in version 9.5.0.76

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.

top
ReceiveUntilByteBdAsync (1)
receive(untilByteBdAsync: Int, bd: CkoBinData) -> CkoTask
Introduced in version 9.5.0.76

Creates an asynchronous task to call the ReceiveUntilByteBd method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveUntilMatch
receive(untilMatch: String) -> String

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.

Important: The method can buffer bytes received beyond the match for the next receive call. This is why ReceivedCount can increase by more than the length returned.

Returns nil on failure

top
ReceiveUntilMatchAsync (1)
receive(untilMatchAsync: String) -> CkoTask

Creates an asynchronous task to call the ReceiveUntilMatch method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ReceiveUntilMatchSb
receive(untilMatchSb: String, sb: CkoStringBuilder) -> Bool
Introduced in version 10.1.0

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.

Note: Bytes read beyond the match can be buffered internally for a later receive operation.

Returns true for success, false for failure.

top
ReceiveUntilMatchSbAsync (1)
receive(untilMatchSbAsync: String, sb: CkoStringBuilder) -> CkoTask
Introduced in version 10.1.0

Creates an asynchronous task to call the ReceiveUntilMatchSb method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
ResetPerf
resetPerf(rcvPerf: Bool)
Introduced in version 9.5.0.78

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.

top
SelectForReading
select(forReading: Int) -> Int

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 valueMeaning
PositiveThe number of sockets in the read-ready set.
0No socket became ready before the timeout.
-1An 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.

Important: Read readiness does not guarantee that application data is present. A receive may instead report that the peer closed or reset the connection.
More Information and Examples
top
SelectForReadingAsync (1)
select(forReadingAsync: Int) -> CkoTask

Creates an asynchronous task to call the SelectForReading method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SelectForWriting
select(forWriting: Int) -> Int

Waits up to timeoutMs for this socket, or sockets in a socket set, to become writable without blocking. Use 0 to poll.

Return valueMeaning
PositiveThe number of sockets in the write-ready set.
0No socket became writable before the timeout.
-1An error occurred.
Note: TCP writes normally complete into the operating-system send buffer. Write readiness does not mean the remote application has received or processed the data.
top
SelectForWritingAsync (1)
select(forWritingAsync: Int) -> CkoTask

Creates an asynchronous task to call the SelectForWriting method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SendBd
sendBd(binData: CkoBinData, offset: UInt, numBytes: UInt) -> Bool
Introduced in version 9.5.0.65

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.

Important: The selected range must be within the BinData. No application message framing is added.

Returns true for success, false for failure.

top
SendBdAsync (1)
sendBdAsync(binData: CkoBinData, offset: UInt, numBytes: UInt) -> CkoTask
Introduced in version 9.5.0.65

Creates an asynchronous task to call the SendBd method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SendByte
sendByte(value: Int) -> Bool
Introduced in version 9.5.0.50

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.

More Information and Examples
top
SendByteAsync (1)
sendByteAsync(value: Int) -> CkoTask
Introduced in version 9.5.0.50

Creates an asynchronous task to call the SendByte method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SendBytes
sendBytes(data: NSData) -> Bool

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.

Important: A successful send does not prove that the remote application received or processed the bytes. TCP acknowledgment and application acknowledgment are different concepts.

Returns true for success, false for failure.

top
SendBytesAsync (1)
sendBytesAsync(data: NSData) -> CkoTask

Creates an asynchronous task to call the SendBytes method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SendBytesENC
sendBytesENC(encodedBytes: String, encodingAlg: String) -> Bool

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.

Important: Malformed encoded input causes the method to fail before or during sending. Check SendFailReason and LastErrorText.
top
SendBytesENCAsync (1)
sendBytesENCAsync(encodedBytes: String, encodingAlg: String) -> CkoTask

Creates an asynchronous task to call the SendBytesENC method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SendCount
sendCount(byteCount: Int) -> Bool

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.

Tip: A length prefix is a common way to frame messages over TCP: send the count first, then exactly that many payload bytes. Validate received lengths before allocating memory or waiting for data.

Returns true for success, false for failure.

top
SendCountAsync (1)
sendCountAsync(byteCount: Int) -> CkoTask

Creates an asynchronous task to call the SendCount method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SendInt16
sendInt16(value: Int, bigEndian: Bool) -> Bool
Introduced in version 9.5.0.50

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.

More Information and Examples
top
SendInt16Async (1)
sendInt16Async(value: Int, bigEndian: Bool) -> CkoTask
Introduced in version 9.5.0.50

Creates an asynchronous task to call the SendInt16 method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SendInt32
sendInt32(value: Int, bigEndian: Bool) -> Bool
Introduced in version 9.5.0.50

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.

top
SendInt32Async (1)
sendInt32Async(value: Int, bigEndian: Bool) -> CkoTask
Introduced in version 9.5.0.50

Creates an asynchronous task to call the SendInt32 method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SendSb
sendSb(sb: CkoStringBuilder) -> Bool
Introduced in version 9.5.0.65

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.

Important: No terminator or length prefix is added. Include any protocol framing in the StringBuilder content.

Returns true for success, false for failure.

top
SendSbAsync (1)
sendSbAsync(sb: CkoStringBuilder) -> CkoTask
Introduced in version 9.5.0.65

Creates an asynchronous task to call the SendSb method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SendString
sendString(str: String) -> Bool

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.

Important: No delimiter, terminator, or length prefix is added automatically. The application must add any framing required by the protocol.

Returns true for success, false for failure.

top
SendStringAsync (1)
sendStringAsync(str: String) -> CkoTask

Creates an asynchronous task to call the SendString method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SendWakeOnLan
sendWake(onLan: String, port: Int, ipBroadcastAddr: String) -> Bool
Introduced in version 9.5.0.69

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.

Important: Wake-on-LAN generally works within a local network segment. Routers commonly block directed broadcasts, and a successful send does not confirm that the target powered on.

Returns true for success, false for failure.

More Information and Examples
top
SendWakeOnLan2
sendWake(onLan2: String, port: Int, ipBroadcastAddr: String, password: String) -> Bool
Introduced in version 9.5.0.77

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.

Important: SecureOn is an optional Wake-on-LAN password field, not encryption and not strong authentication. Support and expected length are device-specific.

Returns true for success, false for failure.

top
SetSslClientCert
setSslClientCert(cert: CkoCert) -> Bool

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.

Important: Configure the client certificate before Connect or ConvertToSsl. A certificate without its private key cannot prove client identity.

Returns true for success, false for failure.

top
SetSslClientCertPem
setSslClientCertPem(pemDataOrPath: String, pemPassword: String) -> Bool

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.

Important: The PEM material must include or make available the private key corresponding to the certificate. Configure it before the TLS handshake begins.

Returns true for success, false for failure.

top
SetSslClientCertPfx
setSslClientCertPfx(pfxPath: String, pfxPassword: String) -> Bool

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.

Important: Protect PFX files and passwords because they contain private-key material.

Returns true for success, false for failure.

top
SleepMs
sleepMs(millisec: Int)

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.

Important: Sleeping blocks the current thread. It is not a substitute for socket readiness methods, asynchronous I/O, or protocol timers.
top
SshAuthenticatePk
sshAuthenticatePk(sshLogin: String, privateKey: CkoSshKey) -> Bool
Introduced in version 9.5.0.50

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.

Important: This authenticates the SSH transport used by the socket tunnel. It does not authenticate the final destination protocol reached through a forwarded channel.

Returns true for success, false for failure.

top
SshAuthenticatePkAsync (1)
sshAuthenticatePkAsync(sshLogin: String, privateKey: CkoSshKey) -> CkoTask
Introduced in version 9.5.0.50

Creates an asynchronous task to call the SshAuthenticatePk method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SshAuthenticatePw
sshAuthenticatePw(sshLogin: String, sshPassword: String) -> Bool
Introduced in version 9.5.0.50

Authenticates the SSH tunnel session using sshLogin and sshPassword. Call SshOpenTunnel first and authenticate before opening forwarded channels.

Important: Do not log or expose the SSH password. Public-key authentication is generally preferable when supported.

Returns true for success, false for failure.

top
SshAuthenticatePwAsync (1)
sshAuthenticatePwAsync(sshLogin: String, sshPassword: String) -> CkoTask
Introduced in version 9.5.0.50

Creates an asynchronous task to call the SshAuthenticatePw method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SshCloseTunnel
sshCloseTunnel() -> Bool
Introduced in version 9.5.0.50

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.

top
SshCloseTunnelAsync (1)
sshCloseTunnelAsync() -> CkoTask
Introduced in version 9.5.0.50

Creates an asynchronous task to call the SshCloseTunnel method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SshNewChannel
sshNewChannel(hostname: String, port: Int, ssl: Bool, maxWaitMs: Int, channel: CkoSocket) -> Bool
Introduced in version 11.0.0

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.

Important: Call SshOpenTunnel and authenticate successfully before opening channels.

Returns true for success, false for failure.

top
SshNewChannelAsync (1)
sshNewChannelAsync(hostname: String, port: Int, ssl: Bool, maxWaitMs: Int, channel: CkoSocket) -> CkoTask
Introduced in version 11.0.0

Creates an asynchronous task to call the SshNewChannel method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
SshOpenTunnel
sshOpenTunnel(sshHostname: String, sshPort: Int) -> Bool
Introduced in version 9.5.0.50

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.

Note: Read inactivity during SSH negotiation is controlled by MaxReadIdleMs.

Returns true for success, false for failure.

top
SshOpenTunnelAsync (1)
sshOpenTunnelAsync(sshHostname: String, sshPort: Int) -> CkoTask
Introduced in version 9.5.0.50

Creates an asynchronous task to call the SshOpenTunnel method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
StartTiming
startTiming()

Starts or restarts the object's convenience timer. Read ElapsedSeconds to obtain the whole number of seconds since this call.

Note: This timer does not affect connection, send, or receive timeouts.
top
TakeConnection
takeConnection(sock: CkoSocket) -> Bool
Introduced in version 9.5.0.77

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.

Important: After a successful transfer, the source object no longer owns the connection and should be treated as disconnected.

Returns true for success, false for failure.

top
TakeSocket
take(sock: CkoSocket) -> Bool

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.

Important: Because ownership is transferred, the source socket object should not be treated as an independent owner of the connection afterward.

Returns true for success, false for failure.

More Information and Examples
top
TlsRenegotiate
tlsRenegotiate() -> Bool
Introduced in version 9.5.0.55

Requests TLS renegotiation on an established TLS connection, causing another handshake to negotiate new security parameters where the protocol and peer support it.

Important: TLS 1.3 does not use legacy renegotiation, and many modern TLS 1.2 servers disable it. The method can therefore fail even on an otherwise healthy TLS connection.

Returns true for success, false for failure.

top
TlsRenegotiateAsync (1)
tlsRenegotiateAsync() -> CkoTask
Introduced in version 9.5.0.55

Creates an asynchronous task to call the TlsRenegotiate method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
UseSsh
useSsh(ssh: CkoSsh) -> Bool
Introduced in version 9.5.0.55

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.

Important: The supplied Ssh object must remain connected and authenticated while the forwarded socket connection is being established and used.

Returns true for success, false for failure.

top

Events

To implement an event callback, your application would define and implement a class that inherits from CkoBaseProgress. Your application can implement methods to override some or all of the default/empty method implementations of the CkoBaseProgress base class.

For example:

class MySocketProgress : CkoBaseProgress {

    override func ProgressInfo(name: String!, value: String!) {
        // application code goes here...
        print(name + ": " + value)
    }

    override func AbortCheck(abort: UnsafeMutablePointer) {
        // application code goes here...
        // To abort the operation, set this equal to true instead of false.
        abort.memory = false
    }

    override func PercentDone(pctDone: NSNumber!, abort: UnsafeMutablePointer) {
        // application code goes here...
        print(pctDone)
        // To abort the operation, set this equal to true instead of false.
        abort.memory = false
    }

    // For asynchronous method calls.
    override func TaskCompleted(task: CkoTask!) {
        // application code goes here...
    }
}

func someAppFunction() {

    // Demonstrate how to set the event callback object...
    let socket = CkoSocket()
    let mySocketProgress = MySocketProgress()
    
    socket.setEventCallbackObject(mySocketProgress)

    // ...
    // ...
    // ...
}

AbortCheck
abortCheck(abort: Bool)

Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.

More Information and Examples
top
PercentDone
percentDone(pctDone: Int, abort: Bool)

This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).

The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.

To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.

More Information and Examples
top
ProgressInfo
progressInfo(name: String, value: String)

This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.

Note: Some Chilkat methods don't fire any ProgressInfo events.

More Information and Examples
top
TaskCompleted
taskCompleted(task: CkoTask)

Called from the background thread when an asynchronous task completes.

top

Deprecated

AcceptNextConnection
acceptNextConnection(maxWaitMs: Int) -> CkoSocket
This method is deprecated and replaced by AcceptNext

Deprecated: This method is deprecated. Use 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.

Important: For a TLS listener, accepting also performs the TLS handshake. The handshake read and write inactivity limits are controlled by MaxReadIdleMs and MaxSendIdleMs. Leaving those values at 0 permits an unresponsive client to keep the handshake waiting indefinitely.

Returns nil on failure

top
AcceptNextConnectionAsync (1) (2)
acceptNextConnectionAsync(maxWaitMs: Int) -> CkoTask
This method is deprecated and replaced by AcceptNext

Creates an asynchronous task to call the AcceptNextConnection method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top
CloneSocket
clone() -> CkoSocket
Introduced in version 9.5.0.47
This method is deprecated and replaced by DupSocket

Deprecated: This method is deprecated. Use 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.

Important: Sharing a connection does not create a second independent protocol session. Coordinate reads, writes, and closing carefully so that one object does not consume bytes or close the connection unexpectedly for the other.

Returns nil on failure

More Information and Examples
top
GetMyCert
getMyCert() -> CkoCert
This method is deprecated and replaced by GetMyServerCert

Deprecated: This method is deprecated. Use 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 nil on failure

top
GetReceivedClientCert
getReceivedClientCert(index: Int) -> CkoCert
This method is deprecated and replaced by GetRcvdClientCert

Deprecated: This method is deprecated. Use 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.

Important: Call this on the accepted connection object returned by AcceptNextConnection, not on the listener. The server application remains responsible for deciding whether the certificate authorizes the client.

Returns nil on failure

top
GetSslServerCert
getSslServerCert() -> CkoCert
This method is deprecated.

Deprecated: This method is deprecated. Use 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 nil on failure

More Information and Examples
top
LastJsonData
lastJsonData() -> CkoJsonObject
Introduced in version 9.5.0.79
This method is deprecated.

Deprecated: This method is deprecated. Use GetLastJsonData instead.

Returns a JSON object containing additional details produced by the most recently called method when such details are available.

Important: Retrieve the data immediately after the operation of interest. A later method call can replace it, and many methods do not produce additional JSON details.

Returns nil on failure

top
SshOpenChannel
sshOpenChannel(hostname: String, port: Int, ssl: Bool, maxWaitMs: Int) -> CkoSocket
Introduced in version 9.5.0.50
This method is deprecated and replaced by SshNewChannel

Deprecated: This method is deprecated. Use 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.

Note: Multiple channels can share one authenticated SSH tunnel and can target different destination endpoints.

Returns nil on failure

top
SshOpenChannelAsync (1) (2)
sshOpenChannelAsync(hostname: String, port: Int, ssl: Bool, maxWaitMs: Int) -> CkoTask
Introduced in version 9.5.0.50
This method is deprecated and replaced by SshNewChannel

Creates an asynchronous task to call the SshOpenChannel method with the arguments provided.

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

top