Author Topic: UDP Client  (Read 2146 times)

sga

  • Newbie
  • *
  • Posts: 3
    • View Profile
UDP Client
« on: June 07, 2012, 07:22:22 AM »
Hello,

I need to activate a UDP client in the firmware to send and receive data using UDP server written in JAVA. Could you give me some guidance on how to use the UDP Client in SBC66EC?

thanks...

PS. This is the code of UDP server in Java
Code: [Select]
package udpserver;

/**
 *
 * @author sga
 */
import java.io.*;
import java.net.*;
import java.util.GregorianCalendar;

class UDPServer {

    public static void main(String args[]) throws Exception {
        if (args.length != 3) {
            System.out.println("Wrong Parameter ---> " + args.length);
        } else {
            int porta = Integer.parseInt(args[0]);
            int packet = Integer.parseInt(args[1]);
            int ora_fine=Integer.parseInt(args[2]);
            GregorianCalendar cl = new GregorianCalendar();
            System.out.println("Start discovery porta ...> "+porta);
            DatagramSocket serverSocket = new DatagramSocket(porta);
            byte[] receiveData = new byte[packet];
            byte[] sendData = new byte[packet];
            boolean ok = true;
            while (ok) {
                System.out.println("Waith data in porta ...> "+porta);
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData());
                System.out.println("RECEIVED: " + sentence);
                InetAddress IPAddress = receivePacket.getAddress();
                int port = receivePacket.getPort();
                String capitalizedSentence = sentence.toUpperCase();
                sendData = capitalizedSentence.getBytes();
                DatagramPacket sendPacket =
                        new DatagramPacket(sendData, sendData.length, IPAddress, port);
                serverSocket.send(sendPacket);
                int ora=cl.HOUR_OF_DAY;
                if(ora>=ora_fine)
                    ok=false;
            }
        }
    }
}


netcruze

  • Jr. Member
  • **
  • Posts: 63
    • View Profile
Re: UDP Client
« Reply #1 on: June 09, 2012, 03:48:34 PM »
Hi, we haven't included a "UDP Client" demo project with the Netcruzer Download yet. But, the Webserver project uses the TCP/IP code from Microchip Application Libraries. So, you can use the examples included with MAL. There are TCP and UDP client examples.

The "BerkeleyUDPClientDemo.c" UDP client (from MAL) is included in the "../src/common_proj/webserver" folder of the Netcruzer Download (no MPLAB project exists for it yet). This is a copy of the file included with MAL. It contains code for a UDP client. The basic steps are to implement a state machine that will fist get the IP address of client via DNS (see SM_NAME_RESOLVE state in example project). After resolving the IP of client, you can send and receive UDP message to and from client (SM_UDP_SEND and SM_UDP_RECV states in code).

This is a copy of the main function in "BerkeleyUDPClientDemo.c"
Code: (c) [Select]
void BerkeleyUDPClientDemo(void)
{
#if defined(STACK_USE_DNS)
NTP_PACKET pkt;
int i;
static DWORD dwServerIP;
static DWORD dwTimer;
    static SOCKET bsdUdpClient;
    int addrlen = sizeof(struct sockaddr_in);
    static struct sockaddr_in udpaddr;
static enum
{
SM_HOME = 0,
SM_NAME_RESOLVE,
SM_CREATE_SOCKET,
//SM_BIND, // Not required since we are sending the first packet
SM_UDP_SEND,
SM_UDP_RECV,
SM_SHORT_WAIT,
SM_WAIT
} SNTPState = SM_HOME;

switch(SNTPState)
{
case SM_HOME:
// Obtain ownership of the DNS resolution module
if(!DNSBeginUsage())
break;

// Obtain the IP address associated with the server name
DNSResolveROM((ROM BYTE*)NTP_SERVER, DNS_TYPE_A);
dwTimer = TickGet();
SNTPState = SM_NAME_RESOLVE;
break;

case SM_NAME_RESOLVE:
// Wait for DNS resolution to complete
if(!DNSIsResolved((IP_ADDR*)&dwServerIP))
{
if((TickGet() - dwTimer) > (5 * TICK_SECOND))
{
DNSEndUsage();
dwTimer = TickGetDiv64K();
SNTPState = SM_SHORT_WAIT;
}
break;
}

// Obtain DNS resolution result
if(!DNSEndUsage())
{
// No valid IP address was returned from the DNS
// server.  Quit and fail for a while if host is not valid.
dwTimer = TickGetDiv64K();
SNTPState = SM_SHORT_WAIT;
break;
}

SNTPState = SM_CREATE_SOCKET;
// No break needed

case SM_CREATE_SOCKET:
bsdUdpClient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(bsdUdpClient == INVALID_SOCKET)
return;

// No explicit binding is necessary since we are going to be the first one
// sending a UDP packet.  sendto() will do implicit binding.  Explicit binding
// is necessary only when creating UDP servers that will be receiving the first
// packet.
// SNTPState = SM_BIND;
// // No break needed
//
// case SM_BIND:
//            udpaddr.sin_port = 0;
//            udpaddr.sin_addr.S_un.S_addr = IP_ADDR_ANY;
//            if( bind(bsdUdpClient, (struct sockaddr*)&udpaddr, addrlen) == SOCKET_ERROR )
//                break;
//
            SNTPState = SM_UDP_SEND;
            // No break needed
           
case SM_UDP_SEND:
            // Transmit a time request packet
memset(&pkt, 0, sizeof(pkt));
pkt.flags.versionNumber = 3; // NTP Version 3
pkt.flags.mode = 3; // NTP Client
pkt.orig_ts_secs = swapl(NTP_EPOCH);
            udpaddr.sin_port = NTP_SERVER_PORT;
            udpaddr.sin_addr.S_un.S_addr = dwServerIP;
if(sendto(bsdUdpClient, (const char*)&pkt, sizeof(pkt), 0, (struct sockaddr*)&udpaddr, addrlen)>0)
            {
dwTimer = TickGet();
                SNTPState = SM_UDP_RECV;
            }
break;

case SM_UDP_RECV:
// Look for a response time packet
i = recvfrom(bsdUdpClient, (char*)&pkt, sizeof(pkt), 0, (struct sockaddr*)&udpaddr, &addrlen);
            if(i < (int)sizeof(pkt))
{
if((TickGet()) - dwTimer > NTP_REPLY_TIMEOUT)
{
// Abort the request and wait until the next timeout period
closesocket(bsdUdpClient);
dwTimer = TickGetDiv64K();
SNTPState = SM_SHORT_WAIT;
break;
}
break;
}
closesocket(bsdUdpClient);
dwTimer = TickGetDiv64K();
SNTPState = SM_WAIT;

// Set out local time to match the returned time
dwLastUpdateTick = TickGet();
dwSNTPSeconds = swapl(pkt.tx_ts_secs) - NTP_EPOCH;
// Do rounding.  If the partial seconds is > 0.5 then add 1 to the seconds count.
if(((BYTE*)&pkt.tx_ts_fraq)[0] & 0x80)
dwSNTPSeconds++;

break;

case SM_SHORT_WAIT:
// Attempt to requery the NTP server after a specified NTP_FAST_QUERY_INTERVAL time (ex: 8 seconds) has elapsed.
if(TickGetDiv64K() - dwTimer > (NTP_FAST_QUERY_INTERVAL/65536ull))
SNTPState = SM_HOME;
break;

case SM_WAIT:
// Requery the NTP server after a specified NTP_QUERY_INTERVAL time (ex: 10 minutes) has elapsed.
if(TickGetDiv64K() - dwTimer > (NTP_QUERY_INTERVAL/65536ull))
SNTPState = SM_HOME;

break;
}

//#if defined(STACK_USE_DNS)
#else
#warning You must define STACK_USE_DNS for BerkeleyUDPClientDemo to work
#endif
}


« Last Edit: June 09, 2012, 03:56:22 PM by netcruze »