Communicating from the phone to the server.

Java for Small Spaces
Can Java phone home?
by Chris Carpenter
Listing 3. Communicating from the phone to the server.


package midp.client;

import javax.microedition.io.*;
import java.util.*;

public class DatagramListener implements Runnable
{
    protected MidpProfileClient client = null;
    protected DatagramConnection datagramConnection = null;
    protected Datagram datagramPacket;
    protected String data = "error";
    protected Vector fileContents = new Vector();
public DatagramListener(MidpProfileClient client, String recvAddr) {
    this.client = client;
    try {
        // Create a connection to listen on the port
        datagramConnection = (DatagramConnection) Connector.open(recvAddr);
    } catch (Exception e) {
        System.out.println("Failed to initialize Connector");
    }
}
protected void closeDatagramConnection() {
    System.out.println("Closing connection");
    if (datagramConnection != null) {
        try {
            datagramConnection.close();
        } catch (Exception f) {
            System.err.println("Failed to close Connector: " + f);
        }
    }
}
public void run() {
    while (true) {
        try {
            System.out.println("Waiting to receive data");
            datagramPacket =
                datagramConnection.newDatagram(datagramConnection.getMaximumLength());
            datagramConnection.receive(datagramPacket);
            System.out.println("received data");
            data = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
            System.out.println("received something");
            data = (new String(datagramPacket.getData())).trim();
            System.out.println("Data : " + data);
            if (data.equals("eof"))
                break;
            fileContents.addElement(data);
        } catch (Exception e) {
            System.out.println("caught exception: " + e.getMessage());
            throw new RuntimeException("Exception receiving packet: " + e.getMessage());
        }
    }
    closeDatagramConnection();
    client.createRecordStore(fileContents);
}
}

About the Author

Chris Carpenter is a software engineer and architect at RoleModel Software, Inc. in Holly Springs, NC. He can be contacted at [email protected].