readline — Read a line of ASCII text from a tcpclient connection using MATLAB-compatible rules.
readline(t) reads text from the remote host associated with tcpclient struct t until a line terminator is found, then returns the characters without that terminator. It preserves MATLAB behavior for timeout handling, buffered partial lines, and closed-connection edge cases.
Syntax
line = readline(client)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
client | Any | Yes | — | tcpclient handle struct. |
Returns
| Name | Type | Description |
|---|---|---|
line | Any | Line text without terminator, empty string, or 0x0 double on timeout. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:readline:InvalidTcpClient | Client handle is missing, malformed, invalid, or stale. | readline: invalid tcpclient handle |
RunMat:readline:NotConnected | Client has no active socket connection. | readline: tcpclient is disconnected |
RunMat:readline:InvalidArguments | Unexpected additional positional arguments are provided. | readline: invalid argument list |
RunMat:readline:InternalError | Internal socket/control-flow conversion fails. | readline: internal socket error |
How readline works
readline(t)waits for data and reads character bytes until the first line feed. The returned value is a MATLAB string scalar that excludes the terminator, mirroring MATLAB’stcpclient.readline.- If the peer uses carriage-return/line-feed pairs (
"\r\n"), RunMat automatically strips both bytes so the returned string matches MATLAB’s behaviour for default CR/LF terminators. - When the terminator is not encountered before the client’s
Timeoutexpires, the builtin returns a 0-by-0 double ([]). Any bytes that arrived remain buffered internally so the nextreadlinecall continues assembling the same logical line. - If the remote host closes the connection before a terminator is observed, the builtin returns the buffered characters (which might be empty) and marks the underlying client as disconnected so subsequent network calls can react accordingly.
- Inputs passed from the GPU are gathered automatically. Networking always runs on the CPU and the returned string is CPU-resident.
- Invalid structs, missing handles, or disconnected clients raise MATLAB-style diagnostics (for example,
RunMat:readline:InvalidTcpClient).
Does RunMat run readline on the GPU?
Networking is exclusively a host-side activity. When a tcpclient struct resides on the GPU, RunMat gathers it back to the CPU before touching the socket. Acceleration providers are not consulted and no GPU buffers are produced. Future GPU-aware networking features will continue to gather metadata automatically so sockets remain purely CPU-bound.
GPU memory and residency
No. RunMat automatically gathers GPU-resident structs before reading from sockets. The returned string lives on the CPU and there is no benefit to calling gpuArray for networking builtins such as readline.
Examples
Reading a newline-terminated response from an echo server
client = tcpclient("127.0.0.1", 55000);
write(client, "ping\n");
reply = readline(client)Expected output:
reply = "ping"Handling CRLF-terminated lines from legacy services
client = tcpclient("legacy.example.com", 1600);
write(client, "HELLO\r\n");
line = readline(client); % CRLF is removed automaticallyExpected output:
line = "OK HELLO"Looping over streaming telemetry one line at a time
client = tcpclient("telemetry.example.com", 9000, "Timeout", 5);
while true
payload = readline(client);
if isequal(payload, [])
continue % timeout, try again once more data arrives
end
disp(payload)
endDetecting closed connections without losing buffered text
client = tcpclient("sensor.example.com", 7000);
try
line = readline(client); % returns partial line if peer closed without LF
disp(line)
readline(client); % second call raises RunMat:readline:NotConnected
catch err
if err.identifier == "RunMat:readline:NotConnected"
disp("Sensor disconnected")
else
rethrow(err)
end
endResponding gracefully to quiet periods with finite timeouts
client = tcpclient("chat.example.com", 4040, "Timeout", 0.5);
msg = readline(client); % returns [] when no line arrives within 0.5 s
if isequal(msg, [])
disp("No complete chat messages yet.")
endParsing numeric payloads that arrive as text lines
client = tcpclient("metrics.example.com", 5050);
line = readline(client);
values = str2double(split(line, ",")); % convert comma-separated numbersLogging line-delimited JSON messages from a service
client = tcpclient("json.example.com", 6000);
while true
payload = readline(client);
if isequal(payload, [])
break
end
decoded = jsondecode(payload);
disp(decoded.status)
endUsing readline with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how readline changes the result.
Run a small readline example, explain the result, then change one input and compare the output.
FAQ
Which terminator does RunMat use?⌄
RunMat currently honours MATLAB’s default line feed (LF, "\n"). Support for configureTerminator will allow other terminators in a future update.
Does readline return the terminator?⌄
No. The terminator bytes are stripped and the MATLAB string contains only the payload characters.
What happens on timeout?⌄
If the terminator is not observed before the configured Timeout, the builtin returns a 0-by-0 double ([]) and retains any buffered bytes so the next call can complete the line once the terminator arrives.
How are CR/LF pairs handled?⌄
When the payload ends with "\r\n", both bytes are removed so the result matches MATLAB’s CR/LF behaviour.
What if the connection closes mid-line?⌄
Any buffered text is returned and subsequent calls raise RunMat:readline:NotConnected, signalling that the socket closed.
Does the builtin perform Unicode validation?⌄
Bytes are decoded using UTF-8. Invalid sequences fall back to lossless byte-to-char mapping so no data is lost.
Can I call readline after gathering a GPU tensor?⌄
Yes. readline gathers arguments automatically and always returns host values.
Will future GPU providers change the return type?⌄
No. Networking results remain CPU strings even when GPUs are available.
Related Io functions
Repl Fs
addpath · cd · copyfile · delete · dir · exist · fullfile · genpath · getenv · ls · mkdir · movefile · path · pwd · rmdir · rmpath · run · savepath · setenv · tempdir · tempname
Tabular
csvread · csvwrite · dlmread · dlmwrite · readmatrix · writematrix
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite
Json
Http
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how readline is executed, line by line, in Rust.
- View the source for readline in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.