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
client- Type
Any- Required
- Yes
- Description
- Live tcpclient value.
Returns
line- Type
Any- Description
- String scalar without its terminator, or a 0-by-0 double on timeout.
Errors
RunMat:network:UnsupportedTarget- When
- A native TCP socket operation is requested in a browser target.
- Message
native TCP sockets are unavailable on this target
RunMat:Cancelled- When
- An invocation is cancelled before or during a pending TCP operation.
- Message
TCP invocation was cancelled
RunMat:readline:InvalidTcpClient- When
- Client handle is missing, malformed, invalid, or stale.
- Message
readline: invalid tcpclient handle
Behavior and output
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’s tcpclient.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 Timeout expires, the builtin returns a 0-by-0 double ([]). Any bytes that arrived remain buffered internally so the next readline call 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).
Host placement
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.
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.
The socket read is a host/network fusion boundary, not a GPU operation. No optional feature is required on native hosts; browser sockets require a separate host capability and are not presently available through this builtin.
Further illustrative programs
Reading a newline-terminated response from an echo server
client = tcpclient("127.0.0.1", 55000);
write(client, "ping\n");
reply = readline(client)
Expected display: 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 automatically
Expected display: 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)
end
Detecting 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
end
Responding 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.")
end
Parsing numeric payloads that arrive as text lines
client = tcpclient("metrics.example.com", 5050);
line = readline(client);
values = str2double(split(line, ",")); % convert comma-separated numbers
Logging 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)
end
Example
Read a deterministic line from a local peer
client = tcpclient('__RUNMAT_LOOPBACK_HOST__', __RUNMAT_LOOPBACK_PORT__);
write(client, uint8(9));
line = readline(client);
disp(line);
close(client);Expected output:
pingUsing 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 · fileattrib · fileparts · filesep · fullfile · genpath · getenv · getpref · isenv · isfile · isfolder · ispref · ls · matlabroot · memmapfile · memmapfile.subsasgn · memmapfile.subsref · mkdir · movefile · open · opentoline · path · pathsep · pcode · pwd · readstruct · rehash · restoredefaultpath · rmdir · rmpath · run · savepath · setenv · setpref · system · tempdir · tempname · uigetdir · uigetfile · uiputfile · unsetenv · userpath · what · winqueryreg · xmlread · xmlwrite
Tabular
arrayDatastore · csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · fileDatastore · getvaropts · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · readtable · readtimetable · setvaropts · setvartype · spreadsheetImportOptions · writecell · writematrix · writetable · writetimetable · xlsread · xlswrite
Data
commit · data.copy · data.create · data.delete · data.exists · data.export · data.import · data.inspect · data.list · data.move · data.open · DataArray.chunk_shape · DataArray.codec · DataArray.dtype · DataArray.fill · DataArray.name · DataArray.rank · DataArray.read · DataArray.resize · DataArray.shape · DataArray.write · Dataset.array · Dataset.arrays · Dataset.attrs · Dataset.begin · Dataset.get_attr · Dataset.has_array · Dataset.id · Dataset.path · Dataset.refresh · Dataset.set_attr · Dataset.set_attrs · Dataset.snapshot · Dataset.version · DataTransaction.abort · DataTransaction.commit · DataTransaction.create_array · DataTransaction.delete_array · DataTransaction.fill · DataTransaction.id · DataTransaction.resize · DataTransaction.set_attr · DataTransaction.set_attrs · DataTransaction.status · DataTransaction.write
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite · readlines · writelines
Import
Json
Source you can read
Every RunMat function's source is public. 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 a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/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.