tcpclient
Create TCP/IP client connection with TCP/IP server
Description
A tcpclient
object represents a connection to a remote host
and remote port from MATLAB® to read and write data. The remote host can be a server or hardware that
supports TCP/IP communication, and must already exist. The tcpclient
object is always the client and cannot be used as a server. For information on creating a
TCP/IP server, see Communicate Using TCP/IP Server Sockets (Instrument Control Toolbox).
Creation
Description
creates a TCP/IP client that connects to a server associated with the remote host
t
= tcpclient(address
,port
)address
and remote port port
. The value
of address
can be either a remote host name or a remote host IP
address. The value of port
must be a number between 1 and 65535.
The input address
sets the Address
property and the
input port
sets the Port
property.
If you specified an invalid address or port, the TCP/IP server is not running, or the connection to the server cannot be established, then the object is not created and MATLAB throws an error.
creates a connection and sets additional Properties using one or
more name-value pair arguments. Set the t
= tcpclient(address
,port
,Name,Value
)Timeout
, ConnectTimeout
, and
EnableTransferDelay
properties using name-value pair arguments. Enclose each property name in quotes,
followed by the property value.
Example: t =
tcpclient("144.212.130.17",80,"Timeout",20,"ConnectTimeout",30)
creates
a TCP/IP client connection to the TCP/IP server on port 80 at IP address
144.212.130.17. It sets the timeout period to 20 seconds and the connection timeout
to 30 seconds.
Properties
Object Creation Properties
Address
— Remote host name or IP address
character vector | string scalar
Remote host name or IP address, specified as a character vector or string scalar. This property can be set only at object creation.
Example: t = tcpclient("www.mathworks.com",80)
creates a
TCP/IP client connection to port 80 at www.mathworks.com.
Example: t = tcpclient("144.212.130.17",80)
creates a TCP/IP
client connection to the TCP/IP server on port 80 at IP address
144.212.130.17.
Data Types: char
| string
Port
— Remote host port
numeric
Remote host port, specified as a number between 1 and 65535, inclusive. This property can be set only at object creation.
Example: t = tcpclient("www.mathworks.com",80)
creates a
TCP/IP client connection to port 4012 at www.mathworks.com.
Data Types: double
Timeout
— Allowed time to complete operations
10 (default) | numeric
Allowed time in seconds to complete read and write operations, specified as a numeric value. Set this property at object creation using a name-value pair argument. You can also change it after object creation using dot notation.
Example: t = tcpclient("144.212.130.17",80,"Timeout",20)
sets
the read/write timeout period to 20 seconds.
Data Types: double
ConnectTimeout
— Allowed time to connect to remote host
Inf
(default) | numeric
Allowed time in seconds to connect to the remote host, specified as a numeric value. This property specifies the maximum time to wait for a connection request to the specified remote host to succeed or fail. This property can be set only at object creation.
Example: t =
tcpclient("144.212.130.17",80,"ConnectTimeout",30)
sets the
connection timeout period to 30 seconds.
Data Types: double
EnableTransferDelay
— Allow delayed acknowledgement from server
true
or 1
(default) | false
or 0
Allow delayed acknowledgement from server, specified as logical
true
or false
. This property indicates
whether Nagle's algorithm is on or off for the connection.
If this property is true
, the client collects small segments
of outstanding data and sends them in a single packet when acknowledgement (ACK)
arrives from the server. Set this property to false
if you want
to immediately send data to the network. If a network is slow, you can improve its
performance by enabling the transfer delay. However, on a fast network
acknowledgements arrive quickly and the difference between enabling or disabling
the transfer delay is negligible.
This property can be set only at object creation.
Example: t =
tcpclient("144.212.130.17",80,"EnableTransferDelay",false)
disables
the transfer delay.
Data Types: logical
Tag
— Label for identifying connection
""
(default) | string
Since R2024a
Label for identifying connection, specified as a string. Use
Tag
to apply a label to a connection that you can use later
to access the connection using tcpclientfind
.
Doing so can be useful when you open a connection in one function and use a
different function to perform operations on the connection. It is also useful for
locating and accessing connections in app callbacks.
Example: t = tcpclient("144.212.130.17",80,"Tag","Sensor")
creates a TCP/IP client with the label "Sensor"
.
Data Types: string
Read and Write Properties
NumBytesAvailable
— Number of bytes available to read
numeric
This property is read-only.
Number of bytes available to read, returned as a numeric value.
Example:
t.NumBytesAvailable
returns the number of bytes available to
read.
Data Types: double
NumBytesWritten
— Total number of bytes written to remote host
0 (default) | numeric
This property is read-only.
Total number of bytes written to the remote host, returned as a numeric value.
Example:
t.NumBytesWritten
returns the number of bytes
written.
Data Types: double
ByteOrder
— Sequential order of bytes
"little-endian"
(default) | "big-endian"
Sequential order in which bytes are arranged into larger numerical values,
specified as "little-endian"
or
"big-endian"
.
Set the value of this property when reading and writing multi-byte data types,
such as uint16
, int16
,
uint32
, int32
, single
,
or double
. The value of this property must match the
configuration of the remote host connected to tcpclient
. The
remote host or other applications might have a default byte order of big-endian,
while the default value of this property is
little-endian
.
Example: t.ByteOrder = "big-endian"
sets the byte order to
big-endian.
Data Types: char
| string
Terminator
— Terminator character for data
"LF"
(default) | "CR"
| "CR/LF"
| 0 to 255
Terminator character for reading and writing ASCII-terminated data, returned as
"LF"
, "CR"
, "CR/LF"
,
or a number from 0 to 255, inclusive. If the read and write terminators are
different, Terminator
is returned as a 1x2 cell array of
these values. Set this property with the configureTerminator
function.
Example: configureTerminator(t,"CR")
sets both the read and
write terminators to "CR"
.
Example: configureTerminator(t,"CR",10)
sets the read
terminator to "CR"
and the write terminator to
10
.
Data Types: double
| char
| string
Callback Properties
BytesAvailableFcnMode
— Bytes available callback trigger mode
"off"
(default) | "byte"
| "terminator"
Bytes available callback trigger mode, returned as "off"
,
"byte"
, or "terminator"
. This setting
determines if the callback is off, triggered by the number of bytes specified by
BytesAvailableFcnCount
, or triggered by the terminator
specified by Terminator
. Set this property with the configureCallback
function.
Example:
configureCallback(t,"byte",50,@callbackFcn)
sets the
callbackFcn
callback to trigger each time 50 bytes of new
data are available to be read.
Example: configureCallback(t,"terminator",@callbackFcn)
sets
the callbackFcn
callback to trigger when a terminator is
available to be read.
Example: configureCallback(dev,"off")
turns off
callbacks.
Data Types: char
| string
BytesAvailableFcnCount
— Number of bytes of data to trigger callback
64 (default) | numeric
Number of bytes of data to trigger the callback specified by
BytesAvailableFcn
, returned as a double. This value is
used only when the BytesAvailableFcnMode
property is
"byte"
. Set these properties with the configureCallback
function.
Example:
configureCallback(t,"byte",50,@callbackFcn)
sets the
callbackFcn
callback to trigger each time 50 bytes of new
data are available to be read.
Data Types: double
BytesAvailableFcn
— Callback function triggered by bytes available event
function handle
Callback function triggered by a bytes available event, returned as a function
handle. A bytes available event is generated
by
receiving a certain number of bytes or a terminator. This property is empty until
you assign a function handle. Set this property with the configureCallback
function.
Example:
configureCallback(t,"byte",50,@callbackFcn)
sets the
callbackFcn
callback to trigger each time 50 bytes of new
data are available to be read.
Data Types: function_handle
ErrorOccurredFcn
— Callback function triggered by error event
function handle
Callback function triggered by an error event, returned as a function handle. An error event is generated when an asynchronous read or write error occurs. This property is empty until you assign a function handle.
Example:
t.ErrorOccurredFcn = @myErrorFcn
Data Types: function_handle
UserData
— General purpose property for user data
any type
General purpose property for user data, returned as any MATLAB data type. For example, you can use this property to store data when an event is triggered from a callback function.
Example:
t.UserData
Object Functions
read | Read data from remote host over TCP/IP |
readline | Read line of ASCII string data from remote host over TCP/IP |
write | Write data to remote host over TCP/IP |
writeline | Write line of ASCII data to remote host over TCP/IP |
configureTerminator | Set terminator for ASCII string communication with remote host over TCP/IP |
configureCallback | Set callback function and trigger condition for communication with remote host over TCP/IP |
flush | Clear buffers for communication with remote host over TCP/IP |
delete | Delete handle object |
clear | Remove items from workspace, freeing up system memory |
Examples
Connect to TCP/IP Remote Host Using Host Name
Create the TCP/IP object t
using the host address shown and port 80
.
t = tcpclient("www.mathworks.com",80)
t = tcpclient with properties: Address: 'www.mathworks.com' Port: 80 NumBytesAvailable: 0 Show all properties, functions
When you connect using a host name, such as a specified web address or 'localhost
', the IP address defaults to IPv6 format. If the server you are connecting to is expecting IPv4 format, connection fails. For IPv4, you can create a connection by specifying an explicit IP address rather than a host name.
Connect to TCP/IP Remote Host Using IP Address
Create a TCP/IP client connection called t
using the IP address shown and port 80
.
t = tcpclient("144.212.130.17",80)
t = tcpclient with properties: Address: '144.212.130.17' Port: 80 NumBytesAvailable: 0 Show all properties, functions
Connect to TCP/IP Remote Host and Set Timeout Period
Create a TCP/IP client connection called t
and set the timeout period to 20 seconds.
t = tcpclient("144.212.130.17",80,"Timeout",20)
t = tcpclient with properties: Address: '144.212.130.17' Port: 80 NumBytesAvailable: 0 Show all properties, functions
ans = 20
See the value of Timeout
.
t.Timeout
The output reflects the property change.
Connect to TCP/IP Remote Host and Set Connection Timeout Period
Create a TCP/IP client connection called t
and set the ConnectTimeout
property to 30 seconds.
t = tcpclient("144.212.130.17",80,"ConnectTimeout",30)
t = tcpclient with properties: Address: '144.212.130.17' Port: 80 NumBytesAvailable: 0 Show all properties, functions
See the value of ConnectTimeout
.
t.ConnectTimeout
ans = 30
The output reflects the property change.
Write and Read uint8 Data from Remote Host
Create a TCP/IP client connection called t
, connecting to a TCP/IP echo server with port 4000. To do so, you must have an echotcpip
server running on port 4000.
echotcpip("on",4000) t = tcpclient("localhost",4000)
t = tcpclient with properties: Address: 'localhost' Port: 4000 NumBytesAvailable: 0 Show all properties, functions
The write
function synchronously writes data to the remote host connected to t
. First specify the data and then write the data. The function suspends MATLAB execution until the specified number of values is written to the remote host.
Assign 10 bytes of uint8
data to the variable data
.
data = uint8(1:10)
data = 1×10 uint8 row vector
1 2 3 4 5 6 7 8 9 10
View the data.
whos data
Name Size Bytes Class Attributes data 1x10 10 uint8
Write data to the echo server.
write(t,data)
Confirm the success of the writing operation by viewing the NumBytesAvailable
property.
t.NumBytesAvailable
ans = 10
Since the client is connected to an echo server, the data you write to the server is returned to the client. Read all the bytes of data available.
read(t)
ans = 1×10 uint8 row vector
1 2 3 4 5 6 7 8 9 10
Using the read
function with no arguments reads all available bytes of data from t
connected to the remote host and returns the data. The number of values read is determined by the NumBytesAvailable
property, which is the number of bytes available in the input buffer.
Close the connection between the TCP/IP client and the remote host by clearing the object. Turn off the echotcpip
server.
clear t echotcpip("off")
Disconnect Single TCP/IP Client Connection
When you use tcpclient
in a script or at the
MATLAB command line, the result is a connection represented by an object in
the MATLAB workspace.
t = tcpclient("192.168.1.2",10000,Timeout=2,Tag="Receive");
t = tcpclient with properties: Address: '192.168.1.2' Port: 10000 Tag: "Receive" NumBytesAvailable: 0
When no references to the same connection exist in other variables, you can disconnect the TCP/IP client by clearing the workspace variable.
clear(t)
Use tcpclientfind
to confirm that the connection is
closed.
tcpclientfind
ans = []
Disconnect TCP/IP Client Connections in Functions or App Callbacks
When you have a tcpclient
connection that exists in the
MATLAB workspace or is saved as a class property or app property, the
tcpclient
object might not be accessible in a different function or app
callback. In this case, you can use tcpclientfind
to find and delete
the connection.
T = tcpclientfind
T = tcpclient with properties: Address: '198.51.100.255' Port: 80 Tag: "" NumBytesAvailable: 0
To close this connection, delete T
.
delete(T)
This command deletes the tcpclient
object and disconnects the client. If you
want to reconnect to the host, you must create a new client interface with
tcpclient
.
After the deletion, calling tcpclientfind
confirms that there are no existing connections.
tcpclientfind
ans = []
Note that the variable T
is still present in the workspace, but it is now an invalid handle.
T
T = handle to deleted tcpclient
The variable persists after deletion of the interface because tcpclient
is a handle object. (For more information about this type of object, see Handle Object Behavior.) You can use clear
to remove the invalid handle from the workspace.
clear T
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
Platform-specific code generation is only supported on desktop platforms (Windows®, macOS, Linux®) and on Raspberry Pi®.
The following
tcpclient
properties do not support code generation:NumBytesAvailable
NumBytesWritten
ByteOrder
Terminator
BytesAvailableFcnMode
BytesAvailableFcnCount
BytesAvailableFcn
ErrorOccurredFcn
UserData
Only
Address
,Port
,Timeout
,ConnectTimeout
, andEnableTransferDelay
are supported.The following
tcpclient
object functions do not support code generation:readline
readbinblock
writeline
writebinblock
writeread
configureTerminator
configureCallback
flush
Only read
and write
are
supported.
Version History
Introduced in R2014bR2024a: New Tag
Property
Use the new Tag
property to apply a label to a connection that you
can use later to access the connection using tcpclientfind
.
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)