Main Content

UDP Communication Between Two Hosts

These are the minimum steps required to communicate between two hosts over UDP.

This example illustrates how you can use UDP objects to communicate between two dedicated hosts. In this example, you know the names of both hosts and the ports they use for communication with each other. One host has the name doejohn.dhpc, using local port 8844, and the other host is doetom.dhpc, using local port 8866.

  1. Create interface objects — Create a UDP object on each host, referencing the other as the remote host.

    On host doejohn.dhpc, create u1. The object constructor specifies the name of the local port to use on the machine where this object is created.

    u1 = udpport("LocalPort",8844)
    u1 = 
    
      UDPPort with properties:
    
         IPAddressVersion: "IPV4"
                LocalHost: "0.0.0.0"
                LocalPort: 8844
        NumBytesAvailable: 0
    
      Show all properties, functions
    

    On host doetom.dhpc, create u2. The object constructor specifies the name of the local port and local host to use on the machine where this object is created.

    u2 = udpport("LocalPort",8866,"LocalHost","doetom.dhpc")
    u2 = 
    
      UDPPort with properties:
    
         IPAddressVersion: "IPV4"
                LocalHost: "172.31.42.41"
                LocalPort: 8866
        NumBytesAvailable: 0
    
      Show all properties, functions
    
  2. Write and read data — Communication between the two hosts is now a matter of sending and receiving data. Write a message from doejohn.dhpc to doetom.dhpc.

    On host doejohn.dhpc, write data to the remote host via u1:

    write(u1,"Ready for data transfer.","string","doetom.dhpc",8866)

    On host doetom.dhpc, read data coming in from the remote host via u2:

    read(u2,u2.NumBytesAvailable,"string")
    ans = 
    
        "Ready for data transfer."
  3. Disconnect and clean up — When you no longer need u1 on host doejohn.dhpc, you should clear the object.

    clear u1

    When you no longer need u2, clear the object on the host doetom.dhpc.

    clear u2

See Also

|

Related Topics