程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> J2ME >> 開發J2ME低級聯網應用

開發J2ME低級聯網應用

編輯:J2ME
在MIDP2.0中提供了如下重要的類對TCP/IP和UDP進行支持。
Javax.microedition.io.SocketConnection
Javax.microedition.io.ServerSocketConnection
Javax.microedition.io.UDPDatagramConnection
今天主要講述在客戶端使用SocketConnection和TCP/IP服務器進行通信,後面的兩個類將在後續的文章中介紹,SocketConnection定義了socket流連接。調用Connector.open("socket://host:port")會返回一個SocketConnection的實例。通過調用socket.openInputStream()和socket.openOutputStream()兩個方法我們將得到InputStream和OutputStream的實例,這樣我們就可以和服務器進行通信了,如下所示:
SocketConnection clIEnt = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
clIEnt.setSocketOption(DELAY, 0);
clIEnt.setSocketOption(KEEPALIVE, 0);
InputStream is = clIEnt.openInputStream();
OutputStream os = clIEnt.openOutputStream();
os.write("some string".getBytes());
int c = 0;
while((c = is.read()) != -1) {
   // do something with the response
}
is.close();
os.close();
clIEnt.close();

    注意在聯網的時候我們還是必須要在另一個線程內進行聯網操作,而不能再主線程進行。這樣的目的是為了避免用戶界面的堵塞。通常我們可以定義一個類擴展Thread類並提供一個把MIDlet作為參數的構造器,為了提高效率我們通過使用wait()和notify()方法,這樣只有在用戶按下按鈕的時候,線程才被喚醒去執行聯網操作,否則再啟動後他一直出去"wait"的狀態。
class CommandThread extends Thread {
    MIDlet parent;

    StreamConnection socket = null;
    InputStream is = null;

    boolean exit = false;

    public CommandThread(MIDlet parent) {
      this.parent = parent;
    }

      public void run() {
        while (!exit) {
          synchronized(parent) {
            while(!commandAvailable) {
              try {
                parent.wait();
              }
              catch (InterruptedException e) {
              }
            }
          }

    ......................
    ..................

    TCP/IP服務器的寫法和一般的服務器寫法是一樣的,因此不再多介紹。如果有問題可以參考Java.Net包的內容。下面通過例子演示一下,我們構建一個時間服務器,在手機端來通過socket訪問並得到當前時間顯示在屏幕上。代碼如下:
import Java.io.BufferedOutputStream;
import Java.io.DataOutputStream;
import Java.io.IOException;
import Java.Net.Socket;
import Java.Net.ServerSocket;
import Java.util.Date;

public class DayTimeServer {

  public static void main(String args[]) {

    int dayTimePort = 13;

    if (args.length == 1) {
      try {
        dayTimePort = Integer.parseInt(args[0]);
      }
      catch (NumberFormatException e) {
        System.out.println("invalid port number");
        System.exit(0);
      }
    }

    ServerSocket serverSocket = null;
    Socket sock;

    DataOutputStream dataout;   

    try {
      serverSocket = new ServerSocket(dayTimePort);
    }
    catch (IOException e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
      System.exit(0);
    }

    while (true) {
      try {
        sock = serverSocket.accept();
        dataout = new DataOutputStream(new BufferedOutputStream
          (sock.getOutputStream()));
        String dateString = new Date().toString();
        dataout.write(dateString.getBytes(),0,dateString.length());
        dataout.flush();
        sock.close();
        }
      catch (IOException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
      }
    }
  }
}

import Javax.microedition.midlet.*;
import Javax.microedition.lcdui.*;

import Java.io.*;
import Javax.microedition.io.*;

public class DayTimeClIEnt extends Javax.microedition.midlet.MIDlet
    implements CommandListener {

  Display display;

  private boolean commandAvailable;
  CommandThread commandThread;
 
  List menu;
  Form outputForm;
  StringItem dt;
     
  Command cmdBack;
  Command cmdExit;

  private static final String PROTOCOL = "socket:";
 
  private String dayTimeURL;

  public void startApp() {
    String host = getAppProperty("HOST");
    String port = getAppProperty("DAYTIME_PORT");
    try {
      (Integer.parseInt(port));
    }
    catch (NumberFormatException e) {
      destroyApp(false);
      notifyDestroyed();
    }
   
    dayTimeURL = PROTOCOL + "//" + host + ":" + port;
    display = Display.getDisplay(this);
    outputForm = new Form("Date/Time");
    dt = new StringItem(null,null);
    outputForm.append(dt);
    cmdBack = new Command("Back",Command.BACK,1);
    outputForm.addCommand(cmdBack);
    cmdExit = new Command("Exit",Command.EXIT,1);
    outputForm.addCommand(cmdExit);
    outputForm.setCommandListener(this);

    menu = new List("Menu",List.IMPLICIT);
    menu.append("Get Date/Time",null);
    menu.append("Exit",null);
    menu.setCommandListener(this);
    display.setCurrent(menu);

    commandAvailable = false;
    commandThread = new CommandThread(this);
    commandThread.start();
  }


  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command cmd, Displayable d) {
    if (cmd == cmdExit) {
      destroyApp(false);
      notifyDestroyed();
    }
    else if (cmd == cmdBack) {
      display.setCurrent(menu);
    }
    else if ((d == menu) && (cmd == List.SELECT_COMMAND)) {
      synchronized (this) {
        commandAvailable = true;
        notify();
      }
    }
  }   

  class CommandThread extends Thread {
    MIDlet parent;

    StreamConnection socket = null;
    InputStream is = null;

    boolean exit = false;

    public CommandThread(MIDlet parent) {
      this.parent = parent;
    }

      public void run() {
        while (!exit) {
          synchronized(parent) {
            while(!commandAvailable) {
              try {
                parent.wait();
              }
              catch (InterruptedException e) {
              }
            }
          }
          commandAvailable = false;
     
          switch (menu.getSelectedIndex()) {
            case 0:
              getDate();
              break;
            case 1:
              exit = true;
          }
        }
        destroyApp(false);
        notifyDestroyed();
      }

    public void getDate() {
      try {
        socket =
          (StreamConnection)Connector.open(dayTimeURL,
             Connector.READ, true);

        is = socket.openInputStream();
      }
      catch (Exception e) {
      }

      try {
        int b;
        StringBuffer sb = new StringBuffer();
        while ( (b = is.read()) != -1) {
          sb.append((char)b);
        }
        socket.close();
        dt.setText(sb.toString());
        display.setCurrent(outputForm);
      }
      catch (Exception e) {
      }
    }
  }
}

你需要在jad文件中定義兩個屬性值,當然你也可以直接寫在源代碼中
DAYTIME_PORT: 13
HOST: 127.0.0.1

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved