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. Note that each host regards the other host's port as the RemotePort:

  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 remote host, the remote port on that other host, and the local port to use on the machine where this object is created:

    u1 = udp('doetom.dhpc', 'RemotePort', 8866, 'LocalPort', 8844)

    On host doetom.dhpc, create u2:

    u2 = udp('doejohn.dhpc', 'RemotePort', 8844, 'LocalPort', 8866)
  2. Connect the objects — Open both UDP objects, so that each can communicate with the other host.

    On host doejohn.dhpc, open u1:

    fopen(u1)

    On host doetom.dhpc, open u2:

    fopen(u2)
  3. 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:

    fprintf(u1, 'Ready for data transfer.')

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

    fscanf(u2)
    ans =
    Ready for data transfer.
  4. Disconnect and clean up — When you no longer need u1 on host doejohn.dhpc, you should disconnect it and remove it from memory and from the MATLAB® workspace.

    fclose(u1)
    delete(u1)
    clear u1

    When you no longer need u2, perform a similar cleanup on the host doetom.dhpc.

    fclose(u2)
    delete(u2)
    clear u2