2012-04-28 47 views
4

我需要帮助,通过bluethooth连接将J2me midlet程序连接到桌面上的java应用程序。如何将安装在移动设备上的J2me Midlet连接到Java应用程序?

如何配置我的midlet应用程序以使用蓝牙连接到桌面应用程序?

设备支持JSR 82 J2ME蓝牙API。这是我的MIDLet代码:

package client; 
//imports 
import javax.microedition.midlet.*; 
import javax.microedition.lcdui.*; 
import javax.microedition.io.*; 
import java.io.*; 

public class client extends MIDlet implements CommandListener { 

    //Variable declaration 
     String pass,user; 
    protected Display display; 
    protected Displayable displayable; 


     StreamConnection stream = null; 
    InputStream in = null; 
    OutputStream out = null; 
    Thread thread = null; 

    Form Login = null; 
     protected Form Message = null; 
     Form Transaction = null; 
     Form Broadcast = null; 
    Form Help = null; 


    TextField txtMessage = null; 
    TextField txtPhone = null; 
     TextField txtacc1 = null; 
    TextField txtacc2 = null; 
    TextField txtsk = null; 
    TextField txtamt = null; 
     TextField txtbc = null; 
     TextField txtuser = null; 
    TextField txtpw = null; 

     Command TransOk = null; 
    Command Back = null; 
     Command Ok = null; 
     Command SmsOk=null; 
    Command SmsDel = null; 
     Command BrdCstOk = null; 
     Command cmdsel = null; 
    Command cmdsel1 = null; 
     Ticker ticker = new Ticker("WELCOME CUSTOMER!"); 
    byte message[] = new byte[200]; 

    private String login[]={"Login"}; 
    private String options[] = {"Inbox", "Write Message", "Transaction","Broadcast", "Help"}; 
    //private String opt[] = { "" }; 
    private List list = null, inbox = null, list1 = null; 

     public void client(){ 

     } 

     public void startApp() { 

      display = Display.getDisplay(this); 

       //First Screen 
       list = new List("Secure SMS", List.IMPLICIT, login, null); 
       list.setTicker(ticker); 
       cmdsel = new Command("Select", Command.OK, 1); 
     list.addCommand(cmdsel); 
     list.setCommandListener(this); 
       display.setCurrent(list); 


       //Login Form 
       Login = new Form("login"); 
     txtuser = new TextField("UserId", "", 10, TextField.NUMERIC); 
     txtpw = new TextField("Password", "", 10, TextField.PASSWORD); 
     Ok = new Command("Enter", Command.OK, 1); 
     Back = new Command("Back", Command.OK, 2); 
     Login.append(txtuser); 
     Login.append(txtpw); 
     Login.addCommand(Ok); 
     Login.setCommandListener(this); 

       //Options 
       list1 = new List("Secure SMS", List.IMPLICIT, options, null); 
       list1.setTicker(ticker); 
       cmdsel1 = new Command("Select", Command.OK, 1); 
     list1.addCommand(cmdsel1); 
     list1.setCommandListener(this); 


       //To Display Inbox Message 
       inbox = new List("Received SMS", List.IMPLICIT); 
     inbox.setTicker(ticker); 
     inbox.addCommand(Back); 
     SmsDel = new Command("Del", Command.OK, 2); 
     inbox.addCommand(SmsDel); 
     inbox.setCommandListener(this); 

       //Write Message Form 
       Message = new Form("Write Message"); 
     txtMessage = new TextField("Message", "", 215, TextField.ANY); 
     txtPhone = new TextField("Mobile", "", 10, TextField.NUMERIC); 
     SmsOk = new Command("ok", Command.OK, 1); 
     Message.setTicker(ticker); 
     Message.append(txtMessage); 
     Message.append(txtPhone); 
     Message.addCommand(SmsOk); 
     Message.addCommand(Back); 
     Message.setCommandListener(this); 


       // TRANSACTION 
     Transaction = new Form("Transaction"); 

     txtacc1 = new TextField("Transfer from A/C", "", 10, TextField.NUMERIC); 
     txtacc2 = new TextField("Transfer to A/C", "", 10, TextField.NUMERIC); 
     txtsk = new TextField("Trans pw", "", 10, TextField.PASSWORD); 
     txtamt = new TextField("Amount", "", 10, TextField.NUMERIC); 

     TransOk = new Command("Enter", Command.OK, 1); 
     Transaction.append(txtacc1); 
     Transaction.append(txtacc2); 
     Transaction.append(txtsk); 
     Transaction.append(txtamt); 
     Transaction.addCommand(TransOk); 
     Transaction.addCommand(Back); 
     Transaction.setCommandListener(this); 


       // BROADCAST 

     txtbc = new TextField("MESSAGE", "", 50, TextField.ANY); 
     BrdCstOk = new Command("ok", Command.OK, 1); 
     Broadcast = new Form("Broadcast"); 
     Broadcast.append(txtbc); 
     Broadcast.addCommand(BrdCstOk); 
     Broadcast.addCommand(Back); 
     Broadcast.setCommandListener(this); 


       // HELP 
     Help = new Form("Help"); 
     Help.append("1.NAVIGATION:\n"); 
     Help.append("Use up,down arrow keys in the cell or in the key-board for selecting the textboxes/n"); 
     Help.append("\n"); 
     Help.append("2.CONTENT TYPING\n"); 
     Help.append("Either type through cell buttons or by keybord after pressing enter key in the keyboard,press 'save' after typing\n"); 
     Help.append("\n"); 
     Help.append("3.INBOX:\n"); 
     Help.append("Inbox enables you to view your messages\n"); 
     Help.append("\n"); 
     Help.append("4.WRITE MESSAGE:\n"); 
     Help.append("Write message enables you to wrtie the message and send it to th number specified in 'mobile' textbox\n"); 
     Help.append("\n"); 
     Help.append("5.TRANSACTION:\n"); 
     Help.append("Type your account no. in 'Account no1' and the account number to be credited in 'Account no2' ,your secret key in 'secret key' and the amount to be transfered in 'Amount',then click 'ok' button for the transaction \n"); 
     Help.append("\n"); 
     Help.append("6.BROADCAST:\n"); 
     Help.append("Type your message and send it to everybody who are connected to the server\n"); 
     Help.append("\n"); 
     Help.addCommand(Back); 
     Help.setCommandListener(this); 




     } 


     public void pauseApp() { 
    } 


    public void destroyApp(boolean unconditional) { 
     display = null; 
     System.out.println("destroyapp"); 
     displayable = null; 
    } 

     public void commandAction(Command c, Displayable d) { 

      // Login 
      if (c == cmdsel) { 
         if (list.getString(list.getSelectedIndex()).equals("Login")){ 
       display.setCurrent(Login); 

       } 
      } 

      // Option Selection 
      if(c == cmdsel1){ 
          if (list1.getString(list1.getSelectedIndex()).equals("Inbox")) { 
       try { 
        System.out.println("inside inbox"); 
        out.flush(); 
        out.write("Inbox;".getBytes()); 
        byte b1[] = new byte[1024]; 
        String buf, temp; 
        in.read(b1); 

        buf = new String(b1); 

        temp = SECURE.decrypt(buf); 

        System.out.println("temp" + temp); 
        if (temp.indexOf('.') != -1) 
         temp = temp.substring(0, temp.indexOf('.')); 
        if (temp.equals("No Message")) { 

         inbox.append("No Message", null); 
        } else { 
         try { 
          int i = 0, j = temp.indexOf(';'); 
          int count = 1; 
          while (j != -1) { 

           inbox.append(temp.substring(i, j), null); 
           i = j + 1; 
           j = temp.indexOf(';', j + 1); 

          } 

         } catch (Exception e1) { 
          System.out.println("exp" + e1); 
         } 
        } 
        display.setCurrent(inbox); 
       } catch (Exception e) { 
        System.out.println("hai" + e); 
       } 
      } 

      if (list1.getString(list1.getSelectedIndex()).equals("Write Message")) { 
       display.setCurrent(Message); 
      } 

      if (list1.getString(list1.getSelectedIndex()).equals("Help")) { 
       display.setCurrent(Help); 
      } 

      if (list1.getString(list1.getSelectedIndex()).equals("Transaction")) { 
       display.setCurrent(Transaction); 
      } 
      if (list1.getString(list1.getSelectedIndex()).equals("Broadcast")) { 
       display.setCurrent(Broadcast); 
      } 
       } 

      // Message delete 
      if (c.equals(SmsDel)) { 
      try { 
       out.write(("Delete" + ";" + inbox.getString(inbox.getSelectedIndex())).getBytes()); 
       for (int i = 0; i < inbox.size(); i++) { 
        inbox.delete(i); 

       } 

      } catch (Exception e) { 
      } 
      display.setCurrent(list1); 
      Alert currentAlert = new Alert("Message deleted"); 
      currentAlert.setTimeout(2500); 
      currentAlert.setString("One Message is deleted"); 
      currentAlert.setType(AlertType.INFO); 
      display.setCurrent(currentAlert); 
     } 



      //login 

     if (c.equals(Ok)) { 
        pass= txtpw.getString(); 
        user=txtuser.getString(); 


        //Server Connection 
       try { 

      stream = (StreamConnection) Connector.open("socket://localhost:9595"); 
      in = stream.openInputStream(); 
      out = stream.openOutputStream(); 
      byte b[] = new byte[50]; 
      out.flush(); 
      out.write(user.getBytes()); 
      in.read(b); 
         } catch (Exception ex) { 
      System.out.println("Exeption " + ex); 
     } 


      if ((user.equals("")) || (user.length() != 10)) { 
       Alert currentAlert = new Alert("Warning"); 
       currentAlert.setTimeout(1500); 
       currentAlert.setString("your userid is wrong or not entered"); 
       currentAlert.setType(AlertType.INFO); 
       display.setCurrent(currentAlert); 
      } else if (pass.equals("") || (pass.length() != 8)) { 
       Alert currentAlert = new Alert("Warning"); 
       currentAlert.setTimeout(1500); 
       currentAlert.setString("Either your pw is wrong or not entered"); 
       currentAlert.setType(AlertType.INFO); 
       display.setCurrent(currentAlert); 
      } else { 
       try { 

        out.flush(); 
        String s11, s22; 
        s11 = SECURE.encrypt(txtuser.getString()); 
        s22 = SECURE.encrypt(txtpw.getString()); 
        System.out.println("s11:"+s11); 
        System.out.println("s22:"+s22); 
        out.write(("login;" + s11 + ";" + s22).getBytes()); 
        byte b11[] = new byte[100]; 
        in.read(b11); 
        String ers1 = new String(b11); 
             System.out.println("ers"+ers1); 
        if (ers1.trim().equals("Error1")) { 

         Alert cur = new Alert("Warning"); 
         cur.setTimeout(3500); 
         cur.setString("Sorry you are not authorized , your userid is wrong"); 
         cur.setType(AlertType.INFO); 
         display.setCurrent(cur); 
         txtuser.setString(""); 
         txtpw.setString(""); 

        } 

        else if (ers1.trim().equals("Error2")) { 

         Alert cur = new Alert("Warning"); 
         cur.setTimeout(3500); 
         cur.setString("Sorry you are not authorized ,your password is wrong"); 
         cur.setType(AlertType.INFO); 
         display.setCurrent(cur); 
         txtuser.setString(""); 
         txtpw.setString(""); 

        } 

        else if (ers1.trim().equals("Error3")) { 

         Alert cur = new Alert("Warning"); 
         cur.setTimeout(3500); 
         cur.setString("login messageYou haven't got enough funds to transfer"); 
         cur.setType(AlertType.INFO); 
         display.setCurrent(cur); 
         txtuser.setString(""); 
         txtpw.setString(""); 

        } else { 
         display.setCurrent(list1); 
         Alert cur = new Alert("Status"); 
         cur.setTimeout(2500); 
         cur.setString("login performed successfully,check your password in inbox"); 
         cur.setType(AlertType.INFO); 
         display.setCurrent(cur); 
         txtuser.setString(""); 
         txtpw.setString(""); 

        } 
       } catch (Exception ex) { 
        System.out.println("Exeption " + ex); 
       } 
      } 
       } 

      if (c.equals(Back)) { 
      display.setCurrent(list1); 
     } 


      // sms 

     if (c.equals(SmsOk)) 

     { 
      if (txtPhone.getString().equals(user)) { 
       Alert currentAlert = new Alert("Warning"); 
       currentAlert.setTimeout(1500); 
       currentAlert.setString("Enter another number"); 
       currentAlert.setType(AlertType.INFO); 
       display.setCurrent(currentAlert); 
      } else if ((txtMessage.getString()).equals("") || (txtMessage.getString().length() < 2)) { 
       Alert currentAlert = new Alert("Warning"); 
       currentAlert.setTimeout(1500); 
       currentAlert.setString("Enter Message"); 
       currentAlert.setType(AlertType.INFO); 
       display.setCurrent(currentAlert); 
      } else if ((txtPhone.getString()).equals("") || (txtPhone.getString().length() != 10)) { 
       Alert currentAlert = new Alert("Warning"); 
       currentAlert.setTimeout(1500); 
       currentAlert.setString("The number field is empty or your own number"); 
       currentAlert.setType(AlertType.INFO); 
       display.setCurrent(currentAlert); 
       txtPhone.setString(""); 
      } else { 
       try { 

        out.flush(); 
        out.write((SECURE.encrypt(txtMessage.getString()) + ";" +SECURE.encrypt(txtPhone.getString())).getBytes()); 
        byte b1[] = new byte[100]; 
        in.read(b1); 
        String ers = new String(b1); 
        display.setCurrent(list1); 
        Alert currentAlert = new Alert("Message sent"); 
        currentAlert.setTimeout(2000); 
        currentAlert.setString("Message sent succesfully"); 
        currentAlert.setType(AlertType.INFO); 
        display.setCurrent(currentAlert); 
        txtPhone.setString(""); 
        txtMessage.setString(""); 

       } catch (Exception ex) { 
        System.out.println("Exeption " + ex); 
       } 
      } 
     } 


      // Transaction 
     if (c.equals(TransOk)) { 

      if ((txtacc1.getString()).equals("") || (txtacc1.getString().length() != 6)) { 
       Alert currentAlert = new Alert("Warning"); 
       currentAlert.setTimeout(1500); 
       currentAlert.setString("Either your account no. is wrong or not entered"); 
       currentAlert.setType(AlertType.INFO); 
       display.setCurrent(currentAlert); 
      } else if ((txtacc2.getString().equals("")) || (txtacc2.getString().length() != 6)) { 
       Alert currentAlert = new Alert("Warning"); 
       currentAlert.setTimeout(1500); 
       currentAlert.setString("Either the account no. is wrong or not entered"); 
       currentAlert.setType(AlertType.INFO); 
       display.setCurrent(currentAlert); 
      } else if ((txtsk.getString().equals("")) || (txtsk.getString().length() >= 4)) { 
       Alert currentAlert = new Alert("Warning"); 
       currentAlert.setTimeout(1500); 
       currentAlert.setString("Either your secret key is wrong or not entered"); 
       currentAlert.setType(AlertType.INFO); 
       display.setCurrent(currentAlert); 
      } else if ((txtamt.getString()).equals("") || (txtamt.getString().length() < 2)) { 
       Alert currentAlert = new Alert("Warning"); 
       currentAlert.setTimeout(1500); 
       currentAlert.setString("Enter Amount"); 
       currentAlert.setType(AlertType.INFO); 
       display.setCurrent(currentAlert); 
      } else { 
       try { 

        out.flush(); 
        String s1, s2, s3, s4; 
        s1 = SECURE.encrypt(txtacc1.getString()); 
        s2 = SECURE.encrypt(txtamt.getString()); 
        s3 = SECURE.encrypt(txtsk.getString()); 
             s4 = SECURE.encrypt(txtacc2.getString()); 


        out.write(("trans;" + s1 + ";" + s2 + ";" + s3 + ";" + s4).getBytes()); 
        byte b1[] = new byte[100]; 
        in.read(b1); 
        String ers = new String(b1); 
             System.out.println("ers"+ers); 
        if (ers.trim().equals("Error1")) { 

         Alert cur = new Alert("Warning"); 
         cur.setTimeout(3500); 
         cur.setString("Sorry you are not authorized ,either one the Account numbers or the secret key is wrong"); 
         cur.setType(AlertType.INFO); 
         display.setCurrent(cur); 
         txtacc1.setString(""); 
         txtacc2.setString(""); 
         txtsk.setString(""); 
         txtamt.setString(""); 

        } 

        else if (ers.trim().equals("Error2")) { 

         Alert cur = new Alert("Warning"); 
         cur.setTimeout(3500); 
         cur.setString("MISUSE Cellnumber and Account number mismatch"); 
         cur.setType(AlertType.INFO); 
         display.setCurrent(cur); 
         txtacc1.setString(""); 
         txtacc2.setString(""); 
         txtsk.setString(""); 
         txtamt.setString(""); 

        } 

        else if (ers.trim().equals("Error3")) { 

         Alert cur = new Alert("Warning"); 
         cur.setTimeout(3500); 
         cur.setString("You haven't got enough funds to transfer"); 
         cur.setType(AlertType.INFO); 
         display.setCurrent(cur); 
         txtacc1.setString(""); 
         txtacc2.setString(""); 
         txtsk.setString(""); 
         txtamt.setString(""); 

        } else if(ers.trim().equals("Success")) { 
         display.setCurrent(list1); 
         Alert cur = new Alert("Status"); 
         cur.setTimeout(2500); 
         cur.setString("Amount transfer performed succesfully"); 
         cur.setType(AlertType.INFO); 
         display.setCurrent(cur); 
         txtacc1.setString(""); 
         txtacc2.setString(""); 
         txtsk.setString(""); 
         txtamt.setString(""); 
        } 
       } catch (Exception ex) { 
        System.out.println("Exeption " + ex); 
       } 
      } 
     } 



      // Broadcast 
     if (c.equals(BrdCstOk)) { 

      if (txtbc.getString().equals("") || (txtbc.getString().length() < 2)) { 
       Alert currentAlert = new Alert("Warning"); 
       currentAlert.setTimeout(1500); 
       currentAlert.setString("Enter Message"); 
       currentAlert.setType(AlertType.INFO); 
       display.setCurrent(currentAlert); 
      } else { 
       try { 
        Alert currentAlert = new Alert("Message sent"); 
        currentAlert.setTimeout(2000); 
        currentAlert.setString("Message sent succesfully"); 
        currentAlert.setType(AlertType.INFO); 
        display.setCurrent(currentAlert); 

        out.flush(); 
        out.write(("bc;" + SECURE.encrypt(txtbc.getString())+"!").getBytes()); 
        byte b1[] = new byte[100]; 
        in.read(b1); 
        txtbc.setString(""); 
        display.setCurrent(list1); 
        Alert cur = new Alert("Status"); 
        cur.setTimeout(2500); 
        cur.setString("Broadcast performed succesfully"); 
        cur.setType(AlertType.INFO); 
        display.setCurrent(cur); 
        txtbc.setString(""); 
       } catch (Exception ex) { 
        System.out.println("Exeption " + ex); 
       } 
      } 
     } 
} 
+0

的这行代码,您的设备是否支持[JSR 82 J2ME蓝牙API(http://stackoverflow.com/tags/jsr82/info “ 'JSR82' 标签维基” )? – gnat 2012-04-28 13:15:28

+0

是的,它支持JSR 82 J2ME蓝牙API .. – heretolearn 2012-04-29 23:18:03

+3

回答[此问题](http://stackoverflow.com/questions/3198306/bluetooth-client-server-communication-between-computer-and-mobile-phone)提及一个应用程序,它不仅连接,而且还实时发送计算机上鼠标光标周围区域的屏幕截图到一个(JSR 82)手机客户端... _ – gnat 2012-07-16 23:27:16

回答

0

下面是使用RFCOMM协议,

客户端和服务器的方案包括蓝牙通信的代码。所以在测试代码之前确保设备已经配对。程序BTServer.java将在桌面计算机上运行,​​并具有蓝牙激活和可见。该程序BTClient.java是一个运行在Mobile上的Midlet。

BTServer.java

package bt; 

import javax.microedition.midlet.*; 
import javax.microedition.lcdui.*; 
import javax.bluetooth.*; 
import javax.microedition.io.*; 
import javax.bluetooth.*; 
import java.io.*; 
import java.util.*; 

public class BTServer implements Runnable 
{ 
    StreamConnectionNotifier notifier=null; 
    StreamConnection conn=null; 
    LocalDevice ld=null; 
    ServiceRecord sr=null; 
    javax.bluetooth.UUID uuid=null; 
    String servurl=null; 
    public Hashtable strht=new Hashtable(); 
    public Hashtable nameht=new Hashtable();  
    public Vector v=new Vector(); 
    public Vector nv=new Vector(); 
    DataInputStream din = null; 
    DataOutputStream dout = null; 
    public gui.Main mid=null; 

    public BTServer(gui.Main m){ 
     mid=m; 
    } 

    public void initServer(){ 
     nv.addElement(mid.logingui.chatname); 
     serverStart(); 
     System.out.println(nv); 
    } 

    public void serverStart(){ 
     uuid=new javax.bluetooth.UUID(0x1003); 
     servurl="btspp://localhost:"+uuid+";name=rfcomm";//;authorize=true"; 
     new Thread(){public void run(){mid.btserverwaitinggui.set();}}.start(); 
     new Thread(this).start(); 
     mid.btserveruserlistgui.setUsers(nv); 
    } 


    public void run() 
    { 
     try{ 
      conn=null; 
      ld=LocalDevice.getLocalDevice(); 
      System.out.println("Device Address:=="+ld.getBluetoothAddress()); 
      ld.setDiscoverable(DiscoveryAgent.GIAC); 
      notifier=(StreamConnectionNotifier)Connector.open(servurl); 
      String st = "hello"; 
      System.out.println("SERVER WAITING FOR CLIENT REQUEST\n"); 
      while(true){ 
       conn = notifier.acceptAndOpen(); 
       System.out.println("CLIENT REQUESTED FOR CONNECTION\n"); 
       RemoteDevice dev = RemoteDevice.getRemoteDevice(conn); 
       System.out.println("Remote device address: "+dev.getBluetoothAddress()); 
       System.out.println("Remote device name: "+dev.getFriendlyName(true)); 
       dout = conn.openDataOutputStream(); 
       din = conn.openDataInputStream(); 
       v.addElement(dout); 
       strht.put(dev.getBluetoothAddress()+"",dout); 
       new Child(din,dev.getBluetoothAddress()+""); 
      }  
     } 
     catch(Exception e){ 
     System.out.println(e);   
     } 
    } 
    /********************************************************/ 

    public class Child extends Thread{ 
     DataInputStream dinc=null; 
     String devddr=null; 
     String chatname=null; 
     public Child(DataInputStream dint,String devt){ 
      try{ 
       devddr=devt; 
       dinc=dint; 
       start(); 
      }catch(Exception e){ 
       // todo: handle exception 
      } 
     } 

     public void run(){  
      try{ 
       String str=null; 
       str=dinc.readUTF(); 
       chatname=str; 
       nv.addElement(chatname); 
       mid.btserveruserlistgui.setUsers(nv); 
       nameht.put(str,devddr); 
       System.out.println(nameht); 
       sendName(str);    
       while(true){ 
        str=dinc.readUTF(); 
        processString(chatname,str); 
       } 
      } 
      catch(Exception e){   
       // todo: handle exception 
      } 
     } 

    } 

    /*****************************************************/ 

    public void sendName(final String nam){ 
     new Thread(){ 
      public void run(){ 
       try{ 
        for(int i=0;i<v.size();i++){ 
         DataOutputStream doo=(DataOutputStream)v.elementAt(i); 
         doo.writeUTF("chatnames"); 
         doo.flush(); 
         for(int j=0;j<nv.size();j++){ 
          String nt=(String)nv.elementAt(j); 
          doo.writeUTF(nt); 
          doo.flush(); 
         } 
         doo.writeUTF("namesend"); 
         doo.flush(); 
        } 
       }catch(Exception e){ 
        // todo: handle exception 
       } 
      } 
     }.start(); 
    } 
    public void processString(String un,String msg){ 
     try { 
      if(msg.indexOf("all")!=-1){ 
       msg=msg.substring(msg.indexOf(":")+1); 
       mid.btserverchatgui.setMessage(msg); 
       sendToAll(msg); 
      } 
      else if(msg.indexOf("one")!=-1){ 
       String to=msg.substring(msg.indexOf(":")+1,msg.indexOf(";")); 
       String mess=msg.substring(msg.indexOf(";")+1); 
       String da=""+nameht.get(to); 
       System.out.println("Device ADDR=="+da); 
       sendToOne(da,mess); 
      } 
      else if(msg.indexOf("server")!=-1){ 
       String mess=msg.substring(msg.indexOf(":")+1); 
       sendToServer(mess); 
      } 
     } catch (Exception e) { 
      // todo: handle exception 
     } 
    } 
    public void sendToAll(final String msg){ 
     new Thread(){ 
      public void run(){ 
       try { 
        for(int i=0;i<v.size();i++){ 

         DataOutputStream doo=(DataOutputStream)v.elementAt(i); 
         doo.writeUTF("msg"); 
         doo.flush(); 
         doo.writeUTF(msg); 
         doo.flush(); 
        } 
       } catch (Exception e) { 
        // todo: handle exception 
       } 
      } 
     }.start(); 
    } 
    public void sendToOne(final String da,final String msg){ 
     new Thread(){ 
      public void run(){ 
       try { 
        DataOutputStream doo=(DataOutputStream)strht.get(da); 
        doo.writeUTF("msg"); 
        doo.flush(); 
        doo.writeUTF(msg); 
        doo.flush(); 
       } catch (Exception e) { 
        // todo: handle exception 
       } 
      } 
     }.start(); 
    } 
    public void sendToServer(String msg){ 
     System.out.println(msg); 
     mid.btserverchatgui.setMessage(msg); 
    } 
}//class 

BTClient.java

import javax.microedition.midlet.*; 
import javax.microedition.lcdui.*; 
import javax.microedition.io.*; 
import java.io.*; 
import javax.bluetooth.*; 
import java.util.*; 

public class BTClient extends MIDlet implements CommandListener,Runnable,DiscoveryListener{ 

    DataOutputStream dout = null; 
    DataInputStream din  = null; 
    StreamConnection s  = null; 
    String address; 
    String serviceUrl; 
    Vector device   = null; 
    Form form    = null; 
    Form addressForm; 
    List devices; 
    Command search,select,back,connect,home,exit; 
    LocalDevice ld; 
    DiscoveryAgent da; 
    Display d = null; 

    public BTClient(){ 
     d=Display.getDisplay(this); 
    } 

    public void startApp(){ 
     initbt(); 
     d.setCurrent(form); 
    } 

    public void destroyApp(boolean f){ 
     if(f) notifyDestroyed(); 
    } 

    public void pauseApp(){} 

    public void initbt(){ 

     try{ 
      device=new Vector(); 
      form = new Form("SEARCH BT DEVICES"); 
      addressForm=new Form("48 Bit Address"); 
      devices=new List("BLUETOOTH DEVICES",List.IMPLICIT); 
      search=new Command("SEARCH",Command.OK,0); 
      back=new Command("BACK",Command.BACK,0); 
      exit=new Command("EXIT",Command.EXIT,0); 
      home=new Command("BACK",Command.BACK,0); 
      select=new Command("OK",Command.OK,1); 
      connect=new Command("CONNECT",Command.OK,0); 
      ld=LocalDevice.getLocalDevice(); 
      //ld.setDiscoverable(DiscoveryAgent.GIAC); 
      da=ld.getDiscoveryAgent(); 
      devices.addCommand(select); 
      devices.addCommand(home); 
      form.addCommand(search); 
      form.addCommand(exit); 
      addressForm.addCommand(back); 
      addressForm.addCommand(connect); 
      devices.setCommandListener(this); 
      addressForm.setCommandListener(this); 
      form.setCommandListener(this); 
     } 
     catch(Exception e) 
     { 
      System.out.println(e); 
     } 
    } 

    public void run(){  
     /* try{ 
     StreamConnection con = null; 
     String url="btspp://"+address+":25;master=false;encrypt=false;authenticate=false"; 
     System.out.println(url); 
     con=(StreamConnection)Connector.open(url); 
     dout = con.openDataOutputStream(); 
     din = con.openDataInputStream(); 
     d.setCurrent(f1); 
     } 
     catch(Exception e){ 
     addressForm.append("ERROR IN CONNECTION"); 
     d.setCurrent(addressForm);  
     }*/ 
    } 

    public void deviceDiscovered(RemoteDevice btDevice,DeviceClass cod){ 
     device.addElement(btDevice); 
    } 

    public void inquiryCompleted(int discType){ 
     System.out.println("In Inquiry completed"); 
     devices.deleteAll(); 
     if(device.size()<=0){ 

      devices.append("size:"+device.size(),null); 
      devices.append("No devices Found",null); 
      d.setCurrent(devices); 
     } 
     else{ 
      for(int i=0;i<device.size();i++){ 

       try{ 
        String devicename = ((RemoteDevice)device.elementAt(i)).getFriendlyName(false); 
        devices.append(devicename,null); 
       } 
       catch(Exception e){ 
        System.out.println(e); 
       } 
      } 
      d.setCurrent(devices); 
     } 
    } 

    public void servicesDiscovered(int transID, ServiceRecord[] servRecord){ 

     System.out.println("ServicesDiscovered"); 
     for(int i=0;i<servRecord.length;i++){ 

      serviceUrl = servRecord[i].getConnectionURL(0,false); 
      System.out.println("Service URL:"+serviceUrl); 
     } 
    } 

    public void serviceSearchCompleted(int transID, int respCode){} 

    public void commandAction(Command c,Displayable dp){ 

     if(c==search){ 
      try{ 
       da.cancelInquiry(this); 
       da.startInquiry(DiscoveryAgent.GIAC,this); 
      } 
      catch(Exception e){ 
       System.out.println("ERROR IN INQUIRY"); 
      } 
     } 
     if(c==connect){ 

      Thread th = new Thread(this); 
      th.start(); 
     } 
     if(c==select){ 
      try{ 
       da.searchServices(null,uuids,((RemoteDevice)device.elementAt(devices.getSelectedIndex())),this); 
      }catch(Exception e){} 

      System.out.println(((RemoteDevice)device.elementAt(0)).getBluetoothAddress()); 
      address=(((RemoteDevice)device.elementAt(devices.getSelectedIndex())).getBluetoothAddress()); 
      addressForm.deleteAll(); 
      addressForm.append("The 48 Bit address of the Bluetooth Device Selected is: "+address); 
      d.setCurrent(addressForm); 
     } 
     if(c==back){ 
      d.setCurrent(devices); 
     } 
     if(c==home) 
      d.setCurrent(form); 
     if(c==exit) 
      destroyApp(true); 
    } 
} 
0

公共gui.Main中期= NULL;

public BTServer(gui.Main m){ 
    mid=m; 
} 

一些错误BTserver

相关问题