read — Read bytes or typed values from a tcpclient connection with MATLAB-compatible behavior.
read(t) consumes data waiting on the TCP/IP client returned by tcpclient (or accept). It follows MATLAB behavior for timeout handling, byte-order decoding, and optional datatype conversion so networking code ports directly.
Syntax
data = read(client)
data = read(client, count)
data = read(client, count, datatype)Inputs
client- Type
Any- Required
- Yes
- Description
- tcpclient object with sealed session-owned socket authority.
count- Type
NumericScalar- Required
- Yes
- Description
- Requested element count.
datatype- Type
StringScalar- Required
- No
- Default
"uint8"- Description
- Data type label (for example "uint8", "double", "char", "string").
Returns
data- Type
Any- Description
- Available bytes or requested typed payload from the TCP client.
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:read:InvalidTcpClient- When
- Client handle is missing, malformed, invalid, or disconnected.
- Message
read: invalid tcpclient handle
Read forms and output classes
data = read(t) waits until at least one byte becomes available (subject to the client timeout) and then drains the socket buffer, returning a row uint8 vector. If the peer closes the connection without sending data, the result is an empty uint8 row vector.
data = read(t, count) blocks until exactly count uint8 values are available (again honouring Timeout). The count may use any native integer class and is read exactly; when the peer closes the socket before satisfying the request the builtin raises RunMat:read:ConnectionClosed.
data = read(t, count, datatype) interprets the values using the requested MATLAB datatype. Supported tokens are "uint8" (default), "int8", "uint16", "int16", "uint32", "int32", "uint64", "int64", "single", "double", "char", and "string". Numeric results retain the requested native class, including exact 64-bit integer values and physical single precision; "char" produces a character row vector and "string" returns a scalar string.
Every call honours the byte order configured when the live client was constructed. Little-endian is the default, but "big-endian" is respected for data written in network byte order; editing a visible copied property does not reconfigure the socket.
The builtin gathers GPU-resident arguments automatically, executes the socket read on the CPU, and returns host values.
Errors are raised with stable identifiers: invalid or stale client objects trigger RunMat:read:InvalidTcpClient, timeouts emit RunMat:read:Timeout, and connection closures before a requested count is met raise RunMat:read:ConnectionClosed.
Host placement and compatibility
Networking is a host-only subsystem. Resident client metadata or count arguments gather transparently before socket I/O. No acceleration-provider hook participates, and the result is always a host value in its selected native numeric class, a character array, or a string.
The socket operation terminates fusion and produces host-owned values. No GPU kernel or provider execution route exists for this identity.
The documented integer count and exact numeric payload classes are preserved; bytes are decoded directly into requested storage without binary64 conversion of 64-bit integers.
Further illustrative programs
Reading a fixed number of bytes from a TCP echo service
client = tcpclient("127.0.0.1", 50000);
write(client, uint8(1:6));
payload = read(client, 6)
Expected display: payload =
1 2 3 4 5 6
Reading ASCII text as characters
client = tcpclient("127.0.0.1", 50001);
write(client, "RunMat TCP");
chars = read(client, 10, "char")
Expected display: chars =
'RunMat TCP'
Reading doubles written in big-endian byte order
client = tcpclient("localhost", 50002, "ByteOrder", "big-endian");
write(client, swapbytes([1 2 3], "double"));
values = read(client, 3, "double")
Expected display: values =
1 2 3
Reading all available data without specifying a count
client = tcpclient("127.0.0.1", 50003);
write(client, uint8([10 20 30]));
burst = read(client)
Expected display: burst =
10 20 30
Handling read timeouts gracefully
client = tcpclient("example.com", 12345, "Timeout", 0.5);
try
data = read(client, 64);
catch err
disp(err.identifier)
end
Expected display: RunMat:read:Timeout
Example
Read exact bytes from a local peer
client = tcpclient('__RUNMAT_LOOPBACK_HOST__', __RUNMAT_LOOPBACK_PORT__);
write(client, uint8(9));
data = read(client, 3, 'uint8');
assert(isa(data, 'uint8'));
assert(isequal(double(data), [1 2 3]));
close(client);Using read with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how read changes the result.
Run a small read example, explain the result, then change one input and compare the output.
FAQ
Does read modify the client object?⌄
No. The builtin uses its sealed session-owned socket authority; visible object properties are not mutated in place.
What happens when the remote host closes the connection?⌄
If the peer closes the connection before the requested count is satisfied, read raises RunMat:read:ConnectionClosed. When no specific count is requested (read(t)), the builtin returns whatever data was available before the closure (possibly an empty vector).
Does read support infinite timeouts?⌄
Yes. Pass "Timeout", inf when constructing the client to leave its socket in blocking mode. Editing the visible client property does not reconfigure the captured live socket.
How are multibyte integers decoded?⌄
RunMat honours the client’s ByteOrder property ("little-endian" or "big-endian"). For example, read(t, 4, "uint16") consumes eight bytes and interprets each pair in the configured byte order.
Can I read UTF-8 strings directly?⌄
The current "string" form maps each received byte directly to a Unicode character of the same value; it does not perform UTF-8 decoding. Use a separate decoder when the peer sends multibyte UTF-8.
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 read is executed, line by line, in Rust.
- View the source for read 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.