← index

TcpSocket

inherits Object

A plaintext TCP connection.

connect:'host:port' dials out (DNS included); every read and write parks the task rather than blocking the scheduler, so thousands of sockets multiplex over one program. The socket itself is byte-level (read: / readAll / writeAll:); for buffering, delimiter framing, or text, hand it to byteStream / stringStream — which *consume* it. Close explicitly (or use connect:do:, which closes on every exit path); a collected socket's fd is reclaimed as a backstop. For an encrypted connection use TlsSocket; for the server side, TcpListener.

TcpSocket.connect:'example.com:80' do:{ |sock|
sock.writeAll:'GET / HTTP/1.0\r\nHost: example.com\r\n\r\n'.asBytes
sock.readAll
}

Class methods

connect:

Connect to 'host:port' (DNS resolved internally) and answer the socket. The caller owns it: close it when done, or prefer connect:do:. Connection failure throws a catchable IoError.

native

connect: do:

Connect, run the block with the socket, and close it on every exit path (normal, throw, or cancel); answers the block's value. The leak-proof form of connect:.

TcpSocket.connect:'example.com:80' do:{ |sock| sock.readAll }

native

Instance methods

byteStream

A buffered ByteStream that *consumes* this socket: the connection transfers to the stream and the socket is left closed (further ops on it throw). Adds read-ahead, peek:, and delimiter framing (readUntil:) over the raw socket.

native

close

Close the socket (idempotent — a second close is a no-op). Further operations throw. Returns nil.

native

closed?

Whether the socket has been closed — including by being consumed into a stream or a TLS upgrade.

native

read:Integer

Up to n bytes as Bytes — one read, so possibly fewer than asked; empty Bytes means the peer closed (EOF). Parks the task until data arrives. Throws on a closed socket or an I/O error. For buffered or delimiter-framed reading, wrap the socket in byteStream.

native

readAll

Read until the peer closes, answering everything as one Bytes. Only returns once the other side signals EOF — for request/response protocols where the peer keeps the connection open, frame reads with read: or a byteStream instead.

native

stringStream

A text StringStream that *consumes* this socket (a byteStream immediately wrapped): readLine / eachLine: / writeln: over the connection, decoding UTF-8.

native

writeAll:Bytes

Write all of the Bytes to the socket — complete or throw, no short writes. Returns nil.

native