Main Content

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

t = tcpclient(address,port) creates a TCP/IP client that connects to a server associated with the remote host 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.

example

t = tcpclient(address,port,Name,Value) creates a connection and sets additional Properties using one or more name-value pair arguments. Set the 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.

example

Properties

expand all

Object Creation Properties

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

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

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

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

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

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

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

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

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 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

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

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

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

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

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

readRead data from remote host over TCP/IP
readlineRead line of ASCII string data from remote host over TCP/IP
writeWrite data to remote host over TCP/IP
writelineWrite line of ASCII data to remote host over TCP/IP
configureTerminatorSet terminator for ASCII string communication with remote host over TCP/IP
configureCallbackSet callback function and trigger condition for communication with remote host over TCP/IP
flushClear buffers for communication with remote host over TCP/IP
deleteDelete handle object
clearRemove items from workspace, freeing up system memory

Examples

collapse all

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.

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

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.

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.

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")

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 =

     []

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

Version History

Introduced in R2014b

expand all