UDP-Client

 

Here is a simple UDP client that can be used with the UDP server shown in the chapter ‎‎19.1.15. As example, assume to have two modules, one in server mode, the second one in client mode.

 

Client side:

set the PORT

set the IP address of the server. The server is already running and waiting a message from client.

start the PDP context

start the UDPClient(): the message "Hello from AppZone!" is sent to the server

 

 

void UDPClient()

{

    M2M_SOCKET_BSD_SOCKET sock;

    struct M2M_SOCKET_BSD_SOCKADDR_IN sa;

    INT32 bytes_sent, buffer_length;

    UINT16 PORT = YYYY;                                               /* ß SET PORT */

    CHAR IP_SERVER[] = "XXX.XXX.XXX.XXX";                /* ß SET THE IP OF THE SERVER */

 

    CHAR buf_send[] = "Hello from AppZone!";

 

    sock = m2m_socket_bsd_socket(M2M_SOCKET_BSD_PF_INET, M2M_SOCKET_BSD_SOCK_DGRAM,

                                                          M2M_SOCKET_BSD_IPPROTO_UDP);

 

 

    if (M2M_SOCKET_BSD_INVALID_SOCKET == sock)

    {

      PrintToUart("Socket handle FAILURE");

      return;

    }

 

    PrintToUart("Socket handle: SUCCESS");                    /* See chapter 19.1.8 PrintToUart */

 

    memset(&sa, 0, sizeof(sa));

    sa.sin_family = M2M_SOCKET_BSD_AF_INET;

    sa.sin_addr.s_addr = m2m_socket_bsd_inet_addr(IP_SERVER);

    sa.sin_port = m2m_socket_bsd_htons(PORT);

 

    bytes_sent = m2m_socket_bsd_send_to(sock, buf_send, sizeof(buf_send), 0,(struct

                                            M2M_SOCKET_BSD_SOCKADDR*)&sa, sizeof (struct M2M_SOCKET_BSD_SOCKADDR_IN));

 

 

    if(bytes_sent >= 0)

    {

      PrintToUart ("Sending: SUCCESS, character sent = %d", bytes_sent);

    }

    else

    {

      PrintToUart ("Sending: FAILURE");

    }

 

    if(m2m_socket_bsd_close(sock) == 0)

    {

      PrintToUart ("Close: SUCCESS");

    }

    else

    {

      PrintToUart ("Close: FAILURE");

    }

 

    return;

}