Chilkat.Socket Class Overview

Chilkat.Socket provides low-level TCP/IP and TLS socket communication for client and server applications. It supports plain TCP, SSL/TLS, client and server certificates, HTTP and SOCKS proxies, SSH tunneling, socket sets, blocking reads and writes, binary and text protocols, performance counters, session logging, and detailed failure diagnostics.

What the Class Is Used For

Use Chilkat.Socket when an application needs direct control over a TCP or TLS connection. It is appropriate for custom protocols, line-oriented protocols, binary protocols, socket servers, TLS client/server handshakes, SSH-tunneled connections, proxied connections, and advanced connection scenarios used by higher-level classes such as Chilkat.Rest.

TCP and TLS Clients Connect to a remote host using plain TCP or SSL/TLS, then send and receive strings, bytes, integers, or streams of protocol data.
Socket Servers Bind to a port, listen for incoming connections, accept clients, and optionally require TLS for accepted connections.
Custom Protocols Read until CRLF, a delimiter byte, a matching string, a fixed byte count, or whatever data is immediately available.
Advanced Routing Connect through HTTP proxies, SOCKS4/SOCKS5 proxies, SSH tunnels, or custom pre-established socket connections.
Low-level class: Socket does not know the rules of protocols such as HTTP, SMTP, FTP, IMAP, or SSH. It provides the transport connection and raw send/receive operations. Higher-level Chilkat classes implement protocol-specific behavior.

Typical Client Workflow

  1. Configure network options such as ClientIpAddress, PreferIpv6, proxy settings, socket buffer sizes, TLS options, or timeouts.
  2. Call Connect(hostname, port, ssl, maxWaitMs) to establish a plain TCP or SSL/TLS connection.
  3. For TLS connections, optionally inspect TlsVersion, TlsCipherSuite, or the server certificate with GetServerCert.
  4. Send data using SendString, SendBytes, SendBd, SendInt16, SendInt32, or related methods.
  5. Receive data using methods such as ReceiveString, ReceiveBytes, ReceiveBdN, ReceiveToCRLF, or ReceiveUntilMatch.
  6. Use LastErrorText, ConnectFailReason, ReceiveFailReason, and SendFailReason to diagnose failures.
  7. Call Close to cleanly close the connection.

Typical Server Workflow

  1. Configure listener options such as ListenIpv6, SoReuseAddr, and optionally UncommonOptions = "ListenAllNetworkInterfaces".
  2. For a TLS server, call InitSslServer with the server certificate before accepting connections.
  3. Optionally call AddSslAcceptableClientCaDn before InitSslServer to identify acceptable client certificate authorities for mutual TLS.
  4. Call BindAndListen or BindAndListenPortRange to begin listening.
  5. Call AcceptNext to accept the next incoming connection into a separate Socket object.
  6. Communicate with the accepted socket using the normal send and receive methods.
  7. Close accepted sockets when finished, and close the listener when the server should stop accepting new clients.
TLS server note: The Ssl property on a listening socket means accepted client connections must use TLS. It does not describe the current connection state. Use TlsVersion to inspect the negotiated TLS version.

Core Concepts

Concept Meaning Important Members
Blocking Operations Most send and receive methods are synchronous and return only after the operation succeeds, fails, times out, or is aborted. SendBytes, ReceiveBytes, MaxReadIdleMs, MaxSendIdleMs
Idle Timeouts Receive operations time out when incoming data stops arriving for too long. Send operations time out when outgoing data cannot continue for too long. MaxReadIdleMs, MaxSendIdleMs
Plain TCP vs TLS A socket can connect directly with TLS, accept TLS clients, or convert an existing plain connection to or from TLS. Connect, ConvertToSsl, ConvertFromSsl, InitSslServer
String Encoding String send/receive methods convert between strings and bytes using the configured character set. StringCharset, SendString, ReceiveString, ReceiveSb
Binary Protocol Support Binary data can be sent and received as byte arrays, encoded strings, BinData, fixed-size integers, or counted frames. SendBytes, ReceiveBytesN, SendCount, ReceiveCount, BigEndian
Socket Sets Multiple connected or listener sockets can be grouped so the application can wait until one or more are ready for reading or writing. TakeSocket, SelectForReading, SelectForWriting, SelectorIndex, SelectorReadIndex
Connection State IsConnected is the last known state and is updated when the application reads, writes, or closes the socket. IsConnected, Close, PollDataAvailable

Connection and Listener Methods

Task Use Notes
Connect to a remote server Connect Connects to a host and port using plain TCP or SSL/TLS. The connect timeout applies to the TCP connect; DNS, proxy, and TLS handshake reads use MaxReadIdleMs.
Close a connection Close Cleanly terminates and closes a TCP, TLS, or SSH channel connection.
Bind and listen on a fixed port BindAndListen Use before accepting incoming connections. Passing port 0 chooses a random unused port, available in ListenPort.
Bind and listen within a port range BindAndListenPortRange Returns the port that was bound, or -1 if no port was available or another failure occurred.
Accept an incoming connection AcceptNext Accepts the next client connection into another Socket object.
Duplicate a connected socket DupSocket Creates another socket object using the same underlying connection, allowing separate threads to read and write.
Transfer one connection to another socket TakeConnection Moves a connection from one socket object to another without creating a socket set.
Add a socket to a socket set TakeSocket Makes the caller a socket set that can contain multiple sockets.

Sending Data

Data Type Methods Use When
String data SendString, SendSb Sending text-based protocol messages. The outgoing bytes are encoded using StringCharset.
Byte arrays SendBytes, SendBytes2 Sending raw binary data.
Encoded binary strings SendBytesENC Sending binary bytes supplied as encoded text, such as hex or Base64.
BinData SendBd Sending all or part of a BinData object.
Single byte SendByte Sending one byte with a value from 0 to 255.
Integer values SendInt16, SendInt32 Sending fixed-width integers in big-endian or little-endian byte order.
Length-prefixed data SendCount Sends a 4-byte count before sending a data block so the receiver knows how many bytes to read.
Wake-on-LAN SendWakeOnLan, SendWakeOnLan2 Sends a Wake-on-LAN magic packet. No prior call to Connect is required.
Send timeout behavior: If sending halts for longer than MaxSendIdleMs, send methods fail and SendFailReason can be checked. A value of 0 means wait indefinitely.

Receiving Data

Receive Pattern Methods Use When
Receive immediately available bytes ReceiveBytes, ReceiveBd, ReceiveSb, ReceiveString Reads what is available, waiting up to MaxReadIdleMs if no data is immediately available.
Receive exactly N bytes ReceiveBytesN, ReceiveBdN, ReceiveNBytesENC Use when a protocol specifies an exact byte count.
Receive to a file ReceiveBytesToFile Appends incoming bytes to a local file.
Receive one byte ReceiveByte Stores the received value in ReceivedInt.
Receive integer values ReceiveInt16, ReceiveInt32 Reads 16-bit or 32-bit integers using the specified byte order.
Receive length-prefixed count ReceiveCount Reads a 4-byte signed integer, often used before reading a following data block.
Receive until CRLF ReceiveToCRLF Common for line-oriented protocols.
Receive until a byte value ReceiveUntilByte, ReceiveUntilByteBd, ReceiveStringUntilByte Use for delimiter-based binary or text protocols.
Receive until a matching string ReceiveUntilMatch, ReceiveUntilMatchSb Useful for reading protocol headers ending in a known marker, such as \r\n\r\n.
Limit string receive size ReceiveStringMaxN Prevents reading more than a specified maximum number of bytes into a string.
Receive timeout behavior: All receive methods stop trying to receive when incoming data stops for more than MaxReadIdleMs. In that case, ReceiveFailReason is set to 5 for timeout.

TLS and Certificate Features

Need Use Notes
Connect with TLS as a client Connect(..., ssl: true, ...) Establishes a TLS connection during the initial connect operation.
Convert a plain connection to TLS ConvertToSsl Useful for protocols that start plain and then upgrade to TLS.
Convert a TLS connection back to plain TCP ConvertFromSsl Closes the secure channel while leaving the underlying socket connected.
Require TLS for accepted client connections InitSslServer, Ssl, AcceptNext Used by server-side sockets. Call InitSslServer before accepting TLS clients.
Use a TLS client certificate SetSslClientCert, SetSslClientCertPem, SetSslClientCertPfx Used only when the server requests or requires client-certificate authentication.
Inspect the server certificate GetServerCert Retrieves the remote server certificate for the current TLS client connection.
Inspect received client certificates NumReceivedClientCerts, GetRcvdClientCert Used on the socket returned by AcceptNext after a mutual TLS handshake.
Require server certificate verification RequireSslCertVerify When true, a TLS client connection fails if the server certificate is expired or cannot be verified.
Specify SNI hostname SniHostname Usually needed only when connecting by IP address but the TLS handshake requires a hostname.
Advertise ALPN protocol AlpnProtocol Adds an ALPN extension to the TLS ClientHello.
Restrict TLS protocol versions SslProtocol Prefer values such as TLS 1.2 or higher instead of requiring one exact version.
Inspect negotiated TLS details TlsVersion, TlsCipherSuite Shows the current or most recently negotiated TLS version and cipher suite.
Pin server public keys TlsPinSet Aborts the TLS handshake if the server certificate’s SPKI fingerprint does not match one of the configured pins.
Renegotiate TLS parameters TlsRenegotiate Initiates a new TLS handshake on an existing TLS connection.
TLS 1.3 note: Chilkat supports TLS 1.3 on the client side. The reference notes that server-side TLS 1.3 is not yet implemented for accepting TLS connections.

Proxy and SSH Tunnel Support

Connection Type Members Purpose
HTTP Proxy HttpProxyHostname, HttpProxyPort, HttpProxyUsername, HttpProxyPassword, HttpProxyAuthMethod, HttpProxyDomain Routes socket connections through an HTTP proxy. Supports Basic and NTLM proxy authentication.
HTTP Proxy for HTTP Protocol HttpProxyForHttp Set to true when the proxied socket will be used to send HTTP requests, such as with Rest.UseConnection.
SOCKS Proxy SocksVersion, SocksHostname, SocksPort, SocksUsername, SocksPassword Supports SOCKS4 and SOCKS5. Set SocksVersion to 4 or 5 to enable.
Open SSH Tunnel SshOpenTunnel, SshAuthenticatePw, SshAuthenticatePk Opens and authenticates an SSH tunnel for port forwarding.
Open SSH Channel SshNewChannel Opens a new forwarded channel through an existing SSH tunnel to a destination host and port.
Use Existing SSH Object UseSsh Routes future socket connections through an already-established Ssh object.
Close SSH Tunnel SshCloseTunnel Closes a tunnel previously opened with SshOpenTunnel.

Socket Sets and Read/Write Selection

A Socket object can become a socket set by calling TakeSocket on one or more connected or listener sockets. This allows an application to wait until any socket in the set is ready for reading or writing.

Need Members Notes
Add sockets to a set TakeSocket Transfers ownership of a connected or listener socket into the socket set.
Count sockets in the set NumSocketsInSet Returns the number of sockets contained in the set.
Route calls to a specific socket SelectorIndex Methods and property access are routed to the socket at this zero-based index.
Wait for readable sockets SelectForReading Returns the number of sockets ready for reading. A disconnected peer can also appear as readable until the application attempts to read.
Select a readable socket from the ready set SelectorReadIndex Used after SelectForReading reports one or more ready sockets.
Wait for writable sockets SelectForWriting Waits until data can be written without blocking.
Select a writable socket from the ready set SelectorWriteIndex Used after SelectForWriting reports one or more writable sockets.

Performance, Buffers, and Network Options

Feature Members Purpose
Receive and send buffer sizes SoRcvBuf, SoSndBuf Adjust low-level socket receive and send buffer sizes. Usually left at defaults.
Application send chunk size SendPacketSize Controls internal chunk size for large sends on non-TLS connections.
Application receive chunk size ReceivePacketSize Controls internal receive size for methods where the byte count is not explicit.
Disable Nagle algorithm TcpNoDelay Can improve responsiveness when sending many small messages.
TCP keepalive KeepAlive Controls the underlying SO_KEEPALIVE socket option.
Reuse listen address SoReuseAddr Applies to sockets that bind and listen. Enabled by default.
Throttle receive or send rate BandwidthThrottleDown, BandwidthThrottleUp Limits receiving or sending bandwidth to approximately the specified bytes per second.
Measure throughput RcvBytesPerSec, SendBytesPerSec, ResetPerf Tracks raw bytes per second, including TLS or SSH protocol overhead.
Track total received bytes ReceivedCount Counts bytes received on the underlying socket. Can be reset by the application.
Convenience timing StartTiming, ElapsedSeconds Provides a simple elapsed-time measurement.

IP Addressing and Local Binding

Need Members Guidance
Choose local source IP ClientIpAddress Use only on multi-homed computers when a specific network interface or local IP address must be used.
Choose local source port ClientPort Usually left at 0. Set only when a remote system requires the connection to originate from a specific client port.
Prefer IPv6 for outbound connections PreferIpv6 Chooses IPv6 when DNS returns both IPv4 and IPv6 addresses.
Listen using IPv6 ListenIpv6 Set before BindAndListen or BindAndListenPortRange.
Listen on all network interfaces UncommonOptions = "ListenAllNetworkInterfaces" Causes the listener socket to bind to 0.0.0.0 instead of 127.0.0.1.
Inspect local endpoint LocalIpAddress, LocalPort Shows the local IP and port for a bound or connected socket.
Inspect remote endpoint RemoteIpAddress, RemotePort Shows the remote peer IP and port for a connected socket.
Get adapter information GetAdaptersAddresses Returns network adapter information, including IPv4, IPv6, and MAC addresses.
Resolve DNS manually DnsLookup, DnsCacheClear Performs DNS lookup or clears Chilkat’s shared in-memory DNS cache.

Diagnostics and Failure Reasons

Socket failures can occur during DNS lookup, TCP connection, proxy negotiation, TLS handshaking, sending, receiving, accepting connections, or peer disconnects. Chilkat exposes separate failure-reason properties for these phases.

Diagnostic Need Use Notes
Detailed text for the last operation LastErrorText Check this whenever a method fails or behaves unexpectedly.
Whether the last method failed LastMethodFailed Helpful for methods where the return value may otherwise be ambiguous.
Connect failure reason ConnectFailReason Indicates whether the failure happened during DNS, TCP connect, TLS handshake, certificate verification, or another connection phase.
Accept failure reason AcceptFailReason Applies to failed AcceptNext calls, including TLS handshake failures for accepted TLS clients.
Receive failure reason ReceiveFailReason Distinguishes timeout, closed peer, reset connection, aborted receive, and other receive failures.
Send failure reason SendFailReason Distinguishes not connected, timeout, closed/reset connection, decoding errors, and other send failures.
Session logging KeepSessionLog, SessionLog, SessionLogEncoding, ClearSessionLog Logs bytes sent and received. Use esc for compact text-like logging or hex for byte-exact logging.
Structured details after selected calls GetLastJsonData Some methods provide additional structured diagnostic data.
Connection-state reminder: IsConnected reflects the last known socket state. A peer may have closed the connection without the local side knowing until the next read or write is attempted.

Best Practices

Recommendation Reason
Set MaxReadIdleMs and MaxSendIdleMs deliberately. The defaults wait indefinitely. Explicit timeouts prevent applications from hanging forever when data stops flowing.
Use StringCharset for text protocols. Text send/receive methods convert bytes using this charset. Set it to the protocol’s required encoding, commonly utf-8.
Use fixed-count receive methods for binary protocols with known lengths. ReceiveBytesN and ReceiveBdN avoid ambiguity when the protocol specifies an exact byte count.
Use delimiter-based receive methods for line-oriented protocols. ReceiveToCRLF and ReceiveUntilMatch simplify protocol parsing.
Check the appropriate failure-reason property after failures. Use ConnectFailReason, AcceptFailReason, ReceiveFailReason, or SendFailReason depending on the operation.
Do not rely on IsConnected alone to detect peer disconnects. A disconnect may not be discovered until the application attempts a read or write.
Use RequireSslCertVerify for production TLS clients when certificate validation is required. It prevents connections to servers with expired or unverifiable certificates.
Use UseConnection from higher-level classes when advanced routing is needed. For example, a Rest object can use a socket that was connected through a proxy, SOCKS server, or SSH tunnel.
Use SessionLogEncoding = "hex" for binary protocol troubleshooting. Hex logging avoids ambiguity when the data is not mostly printable text.

Summary

Chilkat.Socket is the low-level networking class for applications that need direct TCP, TLS, proxy, SSH-tunneled, client/server, or custom protocol communication. It provides precise control over connection setup, socket options, TLS certificates, send and receive patterns, socket sets, timeouts, diagnostics, performance counters, and session logging.

For protocol-specific work, use a higher-level Chilkat class when available. Use Socket when you need raw transport behavior, custom protocol handling, or a pre-established connection for another class.