tcpserver — Create TCP server listeners and return MATLAB-compatible server structs for accept/read/write workflows.
tcpserver(address, port) creates a TCP/IP listening socket and returns a MATLAB-compatible server struct. It validates bind parameters, records listener metadata, and supports downstream workflows with builtins like accept and close.
Syntax
server = tcpserver(address, port)
server = tcpserver(address, port, Name, Value, ...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
address | StringScalar | Yes | — | Bind address or hostname. |
port | NumericScalar | Yes | — | Listening TCP port (0..65535). |
name_value_pairs | Any | Variadic | — | Name/Value options such as Timeout, UserData, Name, and ByteOrder. |
Returns
| Name | Type | Description |
|---|---|---|
server | Any | tcpserver handle struct for accept/close operations. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:tcpserver:InvalidAddress | Address argument is not a valid string scalar. | tcpserver: invalid address argument |
RunMat:tcpserver:InvalidPort | Port argument is non-scalar, non-integer, non-finite, or out of range. | tcpserver: invalid port argument |
RunMat:tcpserver:InvalidNameValue | Name/Value arguments are malformed, unsupported, or have invalid values. | tcpserver: invalid name-value arguments |
RunMat:tcpserver:BindFailed | Socket bind operation fails. | tcpserver: unable to bind listener |
RunMat:tcpserver:InternalError | Internal listener metadata retrieval fails. | tcpserver: internal error |
How tcpserver works
tcpserver(address, port)binds to the requested interface; pass"0.0.0.0"or"::"to listen on every IPv4 or IPv6 adapter respectively.- Ports must be in the range
0–65535. Passing0requests an ephemeral OS-assigned port that RunMat reports in the returned struct. - Supported name-value pairs mirror MATLAB defaults:
Timeout(non-negative seconds, default10),UserData(stored verbatim),Name(defaults to"tcpserver:<address>:<port>"), andByteOrder("little-endian"or"big-endian"). Unsupported options raiseRunMat:tcpserver:InvalidNameValue. - The returned struct mirrors MATLAB properties, including connection state, callback metadata, and an internal
__tcpserver_ididentifier that future networking builtins use to locate the listener. - GPU-resident scalars are gathered automatically before binding so that socket setup always executes on the host CPU.
- Bind failures raise
RunMat:tcpserver:BindFailedwith the OS-provided error message, preserving MATLAB-style diagnostics.
Does RunMat run tcpserver on the GPU?
Networking occurs entirely on the host CPU. If the address or port arguments originate on the GPU, RunMat gathers them before binding the socket. The struct returned by tcpserver is always CPU-resident, and acceleration providers do not need to implement any hooks for this builtin.
GPU memory and residency
No. tcpserver is a host-side operation. RunMat transparently gathers GPU scalars before binding the socket, so keeping address or port values on the GPU provides no performance benefit.
Examples
Creating a loopback TCP server on a fixed port
srv = tcpserver("127.0.0.1", 55000);
disp(srv.ServerAddress)
disp(srv.ServerPort)Expected output:
127.0.0.1
55000Requesting an ephemeral port and inspecting the assigned value
srv = tcpserver("0.0.0.0", 0);
fprintf("Listening on %s:%d\n", srv.ServerAddress, srv.ServerPort)Expected output:
Listening on 0.0.0.0:54873 % actual port varies by runConfiguring the timeout and storing metadata in UserData
srv = tcpserver("localhost", 60000, "Timeout", 5, "UserData", struct("name", "demo"));
disp(srv.Timeout)
disp(srv.UserData.name)Expected output:
5
demoAssigning a custom server name
srv = tcpserver("::1", 45000, "Name", "LoopbackServer");
disp(srv.Name)Expected output:
LoopbackServerSelecting big-endian byte order for binary protocols
srv = tcpserver("127.0.0.1", 45001, "ByteOrder", "big-endian");
disp(srv.ByteOrder)Expected output:
big-endianHandling invalid ports with MATLAB-style diagnostics
try
srv = tcpserver("127.0.0.1", 99999);
catch err
disp(err.identifier)
disp(err.message)
endExpected output:
RunMat:tcpserver:InvalidPort
RunMat:tcpserver:InvalidPort: tcpserver: port 99999 is outside the valid range 0–65535Using tcpserver with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how tcpserver changes the result.
Run a small tcpserver example, explain the result, then change one input and compare the output.
FAQ
What range of ports can I use?⌄
Valid ports are 0–65535. Port 0 lets the OS choose an available ephemeral port, which RunMat reports in the returned struct.
How do I discover which clients are connected?⌄
The returned struct exposes MATLAB-compatible fields (Connected, ClientAddress, ClientPort). Future networking builtins will use the internal __tcpserver_id to inspect active connections.
Does RunMat support IPv6?⌄
Yes. Pass an IPv6 literal (e.g., "::1") or hostname that resolves to IPv6. The returned ServerAddress reflects the bound address.
Can I change the timeout after creating the server?⌄
Not yet. The current builtin records the timeout value for future builtins. A forthcoming setter will update the listener configuration.
Does tcpserver fire callbacks like MATLAB’s BytesAvailableFcn?⌄
Callback-related properties are present for compatibility, and future updates will allow callers to configure them. They currently act as placeholders while connection management matures.
How do I close the server?⌄
A companion builtin (planned) will accept the returned struct and release the underlying listener. Tests can invoke internal helpers until that builtin lands.
Can I use GPU arrays for address or port?⌄
Yes—RunMat gathers them automatically before binding.
What happens if the port is already in use?⌄
tcpserver raises RunMat:tcpserver:BindFailed with the OS error message.
How do I pass additional socket options?⌄
Current support covers Timeout, Name, UserData, and ByteOrder. Additional name-value options (broadcast, reuse, keep-alive) will land alongside their corresponding provider hooks.
Is TLS supported?⌄
Not directly. Combine tcpserver with application-layer protocol helpers or custom TLS wrappers until dedicated support lands.
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 · uigetfile · uiputfile
Tabular
csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · readmatrix · spreadsheetImportOptions · writecell · writematrix · xlsread
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite
Import
Json
Archive
Http
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how tcpserver is executed, line by line, in Rust.
- View the source for tcpserver 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.