Java by API/javax.microedition.io/Connector

Материал из Java эксперт
Перейти к: навигация, поиск

Connector: open(String name) throws IOException

 
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
public class J2METimeServer {
    public static void main(String[] args) {
                
        try {
            Calendar cal = Calendar.getInstance();
            DatagramConnection receiver = 
                    (DatagramConnection)Connector.open("datagram://");
            byte[] buffer = new byte[256];
            Datagram dgram = receiver.newDatagram(buffer, buffer.length);
            for (;;) {
                dgram.setLength(buffer.length);
                receiver.receive(dgram);
                cal.setTime(new Date());
                String time = cal.toString();
                byte[] dataBytes = time.getBytes();
                System.arraycopy(dataBytes, 0, buffer, 0, dataBytes.length);
                dgram.setLength(dataBytes.length);
                receiver.send(dgram);
            }
        } catch (IOException ex) {
            System.out.println("IOException: " + ex);
        }
    }
}





Connector.READ_WRITE

 

import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class HttpMIDlet extends MIDlet implements CommandListener, Runnable {
  private Display display;
  private Form addressForm = new Form("HTTP Client");
  private Form connectForm = new Form("Connecting");
  private Form displayForm = new Form("Server Reply");
  private TextField serverURL = new TextField("URL:", "", 256, TextField.ANY);
  private StringItem messageLabel = new StringItem(null, "Connecting...\nPlease wait.");
  private Command okCommand = new Command("OK", Command.OK, 0);
  private Command exitCommand = new Command("Exit", Command.EXIT, 0);
  private Command backCommand = new Command("Back", Command.BACK, 0);
  
  protected void startApp() throws MIDletStateChangeException {
    display = Display.getDisplay(this);
    addressForm.append(serverURL);
    addressForm.addCommand(okCommand);
    addressForm.addCommand(exitCommand);
    addressForm.setCommandListener(this);
    connectForm.append(messageLabel);
    connectForm.addCommand(backCommand);
    connectForm.setCommandListener(this);
    displayForm.append(messageLabel);
    displayForm.addCommand(backCommand);
    displayForm.setCommandListener(this);
    display.setCurrent(addressForm);
  }
  protected void pauseApp() {
  }
  protected void destroyApp(boolean unconditional)
      throws MIDletStateChangeException {
  }
  public void commandAction(Command cmd, Displayable d) {
    if (cmd == okCommand) {
      Thread t = new Thread(this);
      t.start();
      display.setCurrent(connectForm);
    } else if (cmd == backCommand) {
      display.setCurrent(addressForm);
    } else if (cmd == exitCommand) {
      try {
        destroyApp(true);
      } catch (MIDletStateChangeException ex) {
      }
      notifyDestroyed();
    }
  }
  public void run() {
    InputStream is = null;
    HttpConnection conn = null;
    try {
      String url = serverURL.getString();
      if (!url.startsWith("http://") && !url.startsWith("https://")) {
        url = "http://" + url;
      }
      conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
      if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
        is = conn.openInputStream();
        final int MAX_LENGTH = 128;
        byte[] buf = new byte[MAX_LENGTH];
        int total = 0;
        while (total < MAX_LENGTH) {
          int count = is.read(buf, total, MAX_LENGTH - total);
          if (count < 0) {
            break;
          }
          total += count;
        }
        is.close();
        String reply = new String(buf, 0, total);
        messageLabel.setText(reply);
      } else {
        messageLabel.setText("Failed: error " + conn.getResponseCode() + "\n"+ conn.getResponseMessage());
      }
      conn.close();
      display.setCurrent(displayForm);
    } catch (IOException ex) {
      System.out.println(ex);
      ex.printStackTrace();
      Alert alert = new Alert("I/O Error","An error occurred while communicating with the server.", null,AlertType.ERROR);
      alert.setTimeout(Alert.FOREVER);
      display.setCurrent(alert, addressForm);
      return;
    }
  }
}