Main Content

tcpserver

Create TCP/IP server

    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

    example

    t = tcpserver(address,port) creates a TCP/IP server that listens for a TCP/IP client connection request at the IP address specified by 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.

    example

    t = tcpserver(port) creates a TCP/IP server that listens for a client connection request at port number port and IP address "::". This IP address indicates that the server accepts a client connection from any valid IP address on the machine.

    example

    t = tcpserver(___,Name,Value) creates a TCP/IP server and sets additional Properties using one or more name-value pair arguments. Set the 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

    expand all

    Object Creation Properties

    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

    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

    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

    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

    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

    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

    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

    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

    Read and Write Properties

    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

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

    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

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

    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

    readRead data sent to TCP/IP server
    readlineRead line of ASCII string data sent to TCP/IP server
    readbinblockRead one binblock of data sent to TCP/IP server
    writeWrite data from TCP/IP server
    writelineWrite line of ASCII data from TCP/IP server
    writebinblockWrite one binblock of data from TCP/IP server
    configureTerminatorSet terminator for ASCII string communication
    configureCallbackSet callback function and trigger condition for communication
    flushClear buffers for communication using TCP/IP server

    Examples

    collapse all

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

    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"
    

    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"
    
    Introduced in R2021a