tcpserver
Description
A tcpserver
object represents a TCP/IP server that receives a
TCP/IP client connection request from the specified IP address and port number and accepts the
request. Once the server establishes a connection, you can receive data from and send data to
the client using read and write functions. Each tcpserver
object supports
only one client connection at a
time.
Creation
Description
creates a TCP/IP server that listens for a TCP/IP client connection request at the IP
address specified by t
= tcpserver(address
,port
)address
and the port number specified by
port
.
The input argument address
sets the ServerAddress
property and the input argument
port
sets the ServerPort
property.
creates a TCP/IP server that listens for a client connection request at port number
t
= tcpserver(port
)port
and IP address "::"
. This IP address
indicates that the server accepts a client connection from any valid IP address on the
machine.
creates a TCP/IP server and sets additional Properties using one or more
name-value pair arguments. Set the t
= tcpserver(___,Name,Value
)Timeout
, ByteOrder
, and ConnectionChangedFcn
properties using name-value pair arguments.
After any of the input argument combinations in the previous syntaxes, enclose each
property name in quotes, followed by the property value.
For example, t =
tcpserver(4000,"Timeout",20,"ByteOrder","big-endian")
creates a TCP/IP server
that listens for connections on port 4000
at the IP address
"::"
. It sets the timeout period to 20 seconds and the byte order to
big-endian.
Properties
Object Creation Properties
ServerAddress
— IP address where server listens
"::"
(default) | character vector | string scalar
IP address where the server listens for TCP/IP client connections, specified as a character vector or string scalar. You can set this property to any valid IPV4 address, IPV6 address, or host name of the machine. This property can be set only at object creation.
Example:
t = tcpserver("144.212.100.10",4000)
listens for connections at port
4000 and IP address 144.212.100.10.
Note
If you specify a host name at object creation, tcpserver
resolves it to an IPV4 or IPV6 address and sets ServerAddress
to
the resolved IP address.
Data Types: char
| string
ServerPort
— Port number where server listens
numeric
Port number where the server listens for TCP/IP client connections, specified as a number between 1 and 65535, inclusive. This property can be set only at object creation.
Example:
t = tcpserver("144.212.100.10",4000)
listens for connections at port
4000 and IP address 144.212.100.10.
Data Types: double
Timeout
— Allowed time to complete read and write 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 = tcpserver("144.212.100.10",4000,"Timeout",20)
sets
the read/write timeout period to 20 seconds.
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"
. This only
applies for the following numeric data types: uint16
,
int16
, uint32
, int32
,
uint64
, int64
, single
, and
double
. 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 =
tcpserver("144.212.100.10",4000,"ByteOrder","big-endian")
sets the byte
order to big-endian.
Data Types: char
| string
ConnectionChangedFcn
— Callback function triggered by connection or disconnection event
function handle
Callback function triggered by connection or disconnection event, specified as a function handle. A connection or disconnection event occurs when a TCP/IP client connects to or disconnects from the server. Set this property at object creation using a name-value pair argument. You can also change it after object creation using dot notation. This property is empty until you assign a function handle.
Example: t =
tcpserver("144.212.100.10",4000,"ConnectionChangedFcn",@myConnectionFcn)
sets the connection callback function to myConnectionFcn
. When a
client connects or disconnects, myConnectionFcn
triggers.
Data Types: function_handle
Connection Properties
Connected
— Server connection status
false
or 0
(default) | true
or 1
This property is read-only.
Server connection status, returned as a numeric or logical 1
(true
) or 0
(false
). If the
value of this property is true
, a TCP/IP client is connected to the
server.
You can connect to only one client at a time. If a client disconnects from the server, you can connect to another client immediately.
Data Types: logical
ClientAddress
— IP address of connected client
""
(default) | string scalar
This property is read-only.
IP address of the connected client, returned as a string. The value of this property matches the IP address of the client. The value of this property is empty until a TCP/IP client establishes a connection to the server. If a client disconnects from the server, the value of this property becomes empty.
Example:
t.ClientAddress
returns the IP address of the connected
client.
Data Types: string
ClientPort
— Port number of connected client
[]
(default) | numeric
This property is read-only.
Port number of the connected client, returned as a double. The value of this property is empty until a TCP/IP client establishes a connection to the server.
Example:
t.ClientPort
returns the port number of the connected
client.
Data Types: double
Tag
— Label for identifying server
""
(default) | string
Since R2024a
Label for identifying server, specified as a string. Use Tag
to
apply a label to a server that you can use later to access the server using tcpserverfind
. Doing so can be useful when you create a server in one
function and use a different function to perform operations on the server. It is also
useful for locating and accessing servers in app callbacks.
Example: t.Tag = "Sensor"
sets the label to
"Sensor"
.
Data Types: string
Read and Write Properties
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
numeric integer 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
NumBytesAvailable
— Number of bytes available to read
0 (default) | 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
0 (default) | numeric
This property is read-only.
Total number of bytes written, returned as a numeric value. The value of this property does not reset to 0 when a client disconnects or reconnects to the server.
Example:
t.NumBytesWritten
returns the number of bytes written.
Data Types: double
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(t,"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 the network connection for the server is interrupted or lost. 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 from a callback function.
Example:
t.UserData
Object Functions
read | Read data sent to TCP/IP server |
readline | Read line of ASCII string data sent to TCP/IP server |
readbinblock | Read one binblock of data sent to TCP/IP server |
write | Write data from TCP/IP server |
writeline | Write line of ASCII data from TCP/IP server |
writebinblock | Write one binblock of data from TCP/IP server |
configureTerminator | Set terminator for ASCII string communication |
configureCallback | Set callback function and trigger condition for communication |
flush | Clear buffers for communication using TCP/IP server |
Examples
Create TCP/IP Server that Listens at IP Address and Port Number
Create a TCP/IP server called t
that listens for connections at your machine's IP address and port 4000. Your IP address is different from the one in this example. It must be any valid IPV4 address, IPV6 address, or host name of the adapter on the machine.
t = tcpserver("172.28.200.145",4000)
t = TCPServer with properties: ServerAddress: "172.28.200.145" ServerPort: 4000 Connected: 0 ClientAddress: "" ClientPort: [] NumBytesAvailable: 0 Show all properties, functions
The values of the Connected
, ClientAddress
, and ClientPort
properties indicate that a TCP/IP client is not connected to the server.
Create TCP/IP Server that Listens at Port Number
Create a TCP/IP server called t
that listens for connections at all IP addresses and port 4000.
t = tcpserver(4000)
t = TCPServer with properties: ServerAddress: "::" ServerPort: 4000 Connected: 0 ClientAddress: "" ClientPort: [] NumBytesAvailable: 0 Show all properties, functions
The values of the Connected
, ClientAddress
, and ClientPort
properties indicate that a TCP/IP client is not connected to the server.
Create TCP/IP Server and Set Timeout Period
Create a TCP/IP server called t
and set the read and write timeout period to 20 seconds.
t = tcpserver(4000,"Timeout",20)
t = TCPServer with properties: ServerAddress: "::" ServerPort: 4000 Connected: 0 ClientAddress: "" ClientPort: [] NumBytesAvailable: 0 Show all properties, functions
Display the value of Timeout
.
t.Timeout
ans = 20
The output shows the specified timeout value, indicating that t
waits for up to 20 seconds to complete a read or write operation.
Create TCP/IP Server and Set Connection Event Callback
Create a callback function called connectionFcn
and save it as a .m
file in the current working directory. When this callback function is invoked, it displays a message in the MATLAB Command Window indicating connection or disconnection. You can modify this code to perform read or write operations on your TCP/IP server instead of displaying a message.
function connectionFcn(src,~) if src.Connected disp("This message is sent by the server after accepting the client connection request.") else disp("Client has disconnected.") end end
Create the TCP/IP server called server
and set the ConnectionChangedFcn
property to a handle to the connectionFcn
callback function.
server = tcpserver("localhost",4000,"ConnectionChangedFcn",@connectionFcn)
server = TCPServer with properties: ServerAddress: "127.0.0.1" ServerPort: 4000 Connected: 0 ClientAddress: "" ClientPort: [] NumBytesAvailable: 0 Show all properties, functions
Create a TCP/IP client called client
with the same IP address and port number as your server.
client = tcpclient("localhost",4000)
client = tcpclient with properties: Address: 'localhost' Port: 4000 NumBytesAvailable: 0 Show all properties, functions
This message is sent by the server after accepting the client connection request.
After you create the client, it connects to the server. This triggers a connection event for the server, which invokes the connectionFcn
callback function. The callback function returns the message you see in the Command Window.
Disconnect the client from the server by clearing it.
clear client
Client has disconnected.
Clearing the client triggers a disconnection event for the server and returns the message from the connectionFcn
callback function.
Write String Data from TCP/IP Server
Create a TCP/IP server that listens for a client connection request at the specified port and IP address. Then, write data from the server to the connected client.
Create a TCP/IP server that listens for connections at localhost
and port 4000.
server = tcpserver("localhost",4000)
server = TCPServer with properties: ServerAddress: "127.0.0.1" ServerPort: 4000 Connected: 0 ClientAddress: "" ClientPort: [] NumBytesAvailable: 0 Show all properties, functions
Create a TCP/IP client to connect to your server object using tcpclient
. You must specify the same IP address and port number you use to create server
.
client = tcpclient("localhost",4000)
client = tcpclient with properties: Address: 'localhost' Port: 4000 NumBytesAvailable: 0 Show all properties, functions
See the values of the Connected
, ClientAddress
, and ClientPort
properties for server
.
server
server = TCPServer with properties: ServerAddress: "127.0.0.1" ServerPort: 4000 Connected: 1 ClientAddress: "127.0.0.1" ClientPort: 65136 NumBytesAvailable: 0 Show all properties, functions
The output shows that server
successfully accepts a request from client
and that client
establishes a connection to server
.
Send data to the client by writing it using the server
object. Since the client is connected to the server, this data is available in the client. Read this data from the client
object.
write(server,"hello world","string") read(client,11,"string")
ans = "hello world"
Read String Data Sent to TCP/IP Server
Create a TCP/IP server that listens for a client connection request at the specified port and IP address. Then read data sent to the server from the connected client.
Create a TCP/IP server that listens for connections at localhost
and port 4000.
server = tcpserver("localhost",4000)
server = TCPServer with properties: ServerAddress: "127.0.0.1" ServerPort: 4000 Connected: 0 ClientAddress: "" ClientPort: [] NumBytesAvailable: 0 Show all properties, functions
Create a TCP/IP client to connect to your server object using tcpclient
. You must specify the same IP address and port number you use to create server
.
client = tcpclient("localhost",4000)
client = tcpclient with properties: Address: 'localhost' Port: 4000 NumBytesAvailable: 0 Show all properties, functions
Display the values of the Connected
, ClientAddress
, and ClientPort
properties for server
.
server
server = TCPServer with properties: ServerAddress: "127.0.0.1" ServerPort: 4000 Connected: 1 ClientAddress: "127.0.0.1" ClientPort: 65440 NumBytesAvailable: 0 Show all properties, functions
The output shows that server
successfully accepts a request from client
and that client
establishes a connection to server
.
Write data to the TCP/IP client. Since the client is connected to the server, this data is available in the server. Read the first five values of string data using the server
object.
write(client,"helloworld","string") read(server,5,"string")
ans = "hello"
If you read five more values, you receive the remaining string data.
read(server,5,"string")
ans = "world"
Disconnect TCP/IP Server
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 = tcpserver("localhost",6000,Tag="Analyzer");
t = TCPServer with properties: ServerAddress: "127.0.0.1" ServerPort: 6000 Connected: 0 ClientAddress: "" ClientPort: [] Tag: "Analyzer" NumBytesAvailable: 0
When no references to the same connection exist in other variables, you can disconnect the server by clearing the workspace variable.
clear(t)
Use tcpserverfind
to confirm that the connection is closed.
tcpserverfind
ans = []
Disconnect TCP/IP Servers in Functions or App Callbacks
When you have a tcpserver
connection that exists in
the MATLAB workspace or is saved as a class property or app property, the
tcpserver
object might not be accessible in a different function or
app callback. In this case, you can use tcpserverfind
to find and
delete the connection.
T = tcpserverfind
T = TCPServer with properties: ServerAddress: "127.0.0.1" ServerPort: 6000 Connected: 0 ClientAddress: "" ClientPort: [] Tag: "Analyzer" NumBytesAvailable: 0
To close this connection, delete T
.
delete(T)
This command deletes the tcpserver
object and disconnects the
server. If you want to reconnect to the server, you must create a new server
interface with tcpserver
.
After the deletion, calling tcpserverfind
confirms that there
are no existing connections.
tcpserverfind
ans = []
Note that the variable T
is still present in the workspace, but
it is now an invalid handle.
T
T = handle to deleted tcpserver
The variable persists after deletion of the interface because
tcpserver
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
Version History
Introduced in R2021aR2024a: New Tag
Property
Use the new Tag
property to apply a label to a server that you can
use later to access the server using tcpserverfind
.
Commande MATLAB
Vous avez cliqué sur un lien qui correspond à cette commande MATLAB :
Pour exécuter la commande, saisissez-la dans la fenêtre de commande de MATLAB. Les navigateurs web ne supportent pas les commandes MATLAB.
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)