2 Replies Latest reply: Nov 12, 2007 9:16 PM by 843851 RSS

    can't access services from server using JSR 82

    843851
      hi all,
      i m very much new in this field f witeless technology...i have creater a client-server application using JSR 82 (for Serial Port Profile)where i am willing to send a String from client to server & vice versa...

      the client program is running on NOKIA N70 & server on NOKIA 6600..my client program is detecting all the bluetooth enabled devices & displaying them & then after selecting a particular device when i am trying to get back the available services from the server,then I am not getting services & my client application is not getting the string which i am sending from the server-application..........

      i am giving the code......................

      client-side coding
      ----------------------------------------------------------------------------
      import javax.microedition.midlet.*;
      import javax.microedition.lcdui.*;
      import javax.bluetooth.*;
      import javax.microedition.io.*;
      import java.io.*;

      public class BlueInterface extends MIDlet
      implements CommandListener,DiscoveryListener {
      List main_list;
      List dev_list;
      List serv_list;
      Command exit;
      Command back;
      Display display;
      java.util.Vector devices;
      java.util.Vector services;
      LocalDevice local;
      DiscoveryAgent agent;
      RemoteDevice rd;
      String s;
      private static final UUID uuid = new UUID("102030405060708090A0B0C0D0E0F010", false);
      private UUID[] uuidset;
      private static final int ATTR_ID=0x0008;
      ServiceRecord sr;

      public void startApp() {
      main_list = new List("Select Operation",Choice.IMPLICIT); //the main menu
      dev_list = new List("Select Device",Choice.IMPLICIT); //the list of devices
      serv_list = new List("Available Services",Choice.IMPLICIT); //the list of services
      exit = new Command("Exit",Command.EXIT,1);
      back = new Command("Back",Command.BACK,1);
      display = Display.getDisplay(this);

      main_list.addCommand(exit);
      main_list.setCommandListener(this);
      dev_list.addCommand(exit);
      dev_list.setCommandListener(this);
      serv_list.addCommand(exit);
      serv_list.addCommand(back);
      serv_list.setCommandListener(this);

      main_list.append("Find Devices",null);
      display.setCurrent(main_list);

      }
      public void commandAction(Command com, Displayable dis) {
      if (com == exit){                                              //exit triggered from the main form
      destroyApp(false);
      notifyDestroyed();
      }
      if (com == List.SELECT_COMMAND){
      if (dis == main_list){                                     //select triggered from the main from
      if (main_list.getSelectedIndex() >= 0){                //find devices
      FindDevices();
      do_alert("Searching for devices...", Alert.FOREVER);
      }
      }
      if (dis == dev_list){                                       //select triggered from the device list
      //if (dev_list.getSelectedIndex() >= 0){                  //find services
      int[] attributes = new int[1];
      attributes[0] =ATTR_ID; //the name of the service
      uuidset = new UUID[2];
      uuidset[0] = new UUID(0x1101); //browsable services
      uuidset[1] = uuid;
      rd=getSelectedDevice();
      FindServices(attributes,uuidset,rd);
      do_alert("Inquiring device for services...", Alert.FOREVER);

      //}
      }
      }
      /*if(dis==serv_list)
      {
           if(serv_list.getSelectedIndex()>=0)
           {
           send_SPP_message(getFirstDiscoveredServices(),"hiiiiiiiiiiii server");
           serv_list.append(s,null);
           }
      }*/
      if (com == back){
      if (dis == serv_list){                                    //back button is pressed in devices list
      display.setCurrent(dev_list);
      }
      }

      }


      public void FindDevices(){
      try{
      devices = new java.util.Vector();
      LocalDevice local = LocalDevice.getLocalDevice();
      DiscoveryAgent agent = local.getDiscoveryAgent();
      agent.startInquiry(DiscoveryAgent.GIAC,this);
      }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);}
      }

      public void FindServices(int[] attributes, UUID[] uuids, RemoteDevice device){
      try{
      services = new java.util.Vector();
      local = LocalDevice.getLocalDevice();
      agent = local.getDiscoveryAgent();
      serv_list.deleteAll(); //empty the list of services
      //in case user has pressed back
      agent.searchServices(attributes,uuids,device,this);
      }catch(Exception e){this.do_alert("Erron in initiating search" , 4000);}
      }

      public RemoteDevice getSelectedDevice()
      {
           if(dev_list.getSelectedIndex()>=0)
           return (RemoteDevice)devices.elementAt(dev_list.getSelectedIndex());
           else
           return null;
      }


      /*public ServiceRecord getFirstDiscoveredServices()
      {
           //services=new java.util.Vector();
           if(services.size()>0)
           return (ServiceRecord)services.elementAt(0);
           else
           return null;
      } */

      /* public void send_SPP_message(ServiceRecord r, String msg)
      {
                
           String url=r.getConnectionURL(
      ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
           try
           {
                StreamConnection con= (StreamConnection)Connector.open( url );
      //byte buffer[]=new buffer[100];
      //String msg="hiiiiiiiii server";
      DataInputStream in=con.openDataInputStream();
                DataOutputStream out=con.openDataOutputStream();
      out.writeUTF(msg);
      out.flush();
      Thread.sleep(1000);
      out.close();
      s=in.readUTF();
      //in.close();
      con.close();
      }
      catch(IOException e)
           {
           e.printStackTrace();               
           }
           catch(InterruptedException e)
           {
                e.printStackTrace();          
           }
           
      }*/

      public void deviceDiscovered(RemoteDevice remoteDevice,DeviceClass deviceClass) {
      devices.addElement(remoteDevice);
      }

      public void servicesDiscovered(int transID,ServiceRecord[] serviceRecord) {
      for (int x = 0; x < serviceRecord.length; x++ )
      {
           //services.addElement(serviceRecord[x]);
           DataElement ser_de = serviceRecord[x].getAttributeValue(ATTR_ID);
           String serviceName = (String)ser_de.getValue();
           if(serviceName.equals("SPPserver"))
      {
      String url=serviceRecord[x].getConnectionURL(
      ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
           try
           {
                StreamConnection con= (StreamConnection)Connector.open( url );
      //byte buffer[]=new buffer[100];
      String msg="hiiiiiiiii server";
      DataInputStream in=con.openDataInputStream();
                DataOutputStream out=con.openDataOutputStream();
      out.writeUTF(msg);
      out.flush();
      Thread.sleep(1000);
      out.close();
      s=in.readUTF();
      //in.close();
      con.close();
      }
      catch(IOException e)
           {
           e.printStackTrace();               
           }
           catch(InterruptedException e)
           {
                e.printStackTrace();          
           }
      /*send_SPP_message(serviceRecord[x],"hiiiiiiiiiiii server");*/
      serv_list.append(s,null);
      display.setCurrent(serv_list);
      }
           //if(sr!=null)return;
           /*sr=serviceRecord[0];
           if(serviceName.equals(""))
           send_SPP_message(serviceRecord[x],"Hiiiiiiiiiiiiiii SERVER");
           serv_list.append(s,null);
      display.setCurrent(serv_list);*/
           
      }
      //services.addElement(serviceRecord[x]);
      }
      public void inquiryCompleted(int param){
      switch (param) {
      case DiscoveryListener.INQUIRY_COMPLETED: //Inquiry completed normally
      for(int x = 0; x < devices.size(); x++ )
      try{
      String device_name = ((RemoteDevice)devices.
      elementAt(x)).getFriendlyName(false);
      this.dev_list.append(device_name , null);
      display.setCurrent(dev_list);
      }catch (Exception e){do_alert("Error in adding devices",4000);}
      break;
      case DiscoveryListener.INQUIRY_ERROR: // Error during inquiry
      this.do_alert("Inqury error" , 4000);
      break;
      case DiscoveryListener.INQUIRY_TERMINATED: // Inquiry terminated by agent.cancelInquiry()
      this.do_alert("Inqury Canceled" , 4000);
      break;
      }
      }

      public void serviceSearchCompleted(int transID, int respCode) {
      switch(respCode) {
      case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
      /*for(int x = 0; x < services.size(); x++ )
      try{
      DataElement ser_de = ((ServiceRecord)services.
      elementAt(x)).getAttributeValue(ATTR_ID);
      String service_name = (String)ser_de.getValue();
      if(service_name.equals("server application"))
      {
      send_SPP_message(getFirstDiscoveredServices(),"hiiiiiiiiiiii server");
      serv_list.append(s,null);
      display.setCurrent(serv_list);
      }
      serv_list.append(service_name ,null);
      display.setCurrent(serv_list);
      }catch (Exception e){do_alert("Error in adding services " ,1000);}*/
      this.do_alert("Connection completed" , 4000);

      break;
      case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
      this.do_alert("Device not Reachable" , 4000);
      break;
      case DiscoveryListener.SERVICE_SEARCH_ERROR:
      this.do_alert("Service serch error" , 4000);
      break;
      case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
      this.do_alert("No records returned" , 4000);
      break;
      case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
      this.do_alert("Inqury Cancled" , 4000);
      break;
      }
      }

      public void do_alert(String msg,int time_out){
      if (display.getCurrent() instanceof Alert ){
      ((Alert)display.getCurrent()).setString(msg);
      ((Alert)display.getCurrent()).setTimeout(time_out);
      }else{
      Alert alert = new Alert("Bluetooth");
      alert.setString(msg);
      alert.setTimeout(time_out);
      display.setCurrent(alert);
      }
      }

      public void pauseApp() {}

      public void destroyApp(boolean unconditional) {}

      }

      server-side coding
      -------------------------------------------------------------------------
      package bluetooth;
      import javax.microedition.io.*;
      import javax.bluetooth.*;
      import java.util.*;
      import java.io.*;



      public class bluetooth_server implements Runnable{


      LocalDevice localdevice;
      DiscoveryAgent agent;
      //private ServiceRecord record;
      //private String addr;
      public String s;

      // SPP_Server specific service UUID
      // note: this UUID must be a string of 32 char
      // do not use the 0x???? constructor because it won't
      // work. not sure if it is a N6600 bug or not
      private static final UUID uuid = new UUID("102030405060708090A0B0C0D0E0F010", false);
      private static final int ATTR_ID=0x0008;
      private final static int SERVICE_TELEPHONY = 0x400000;
      //
      // major service class as SERVICE_TELEPHONY
      //ivate final static int SERVICE_TELEPHONY = 0x400000;

      ServiceRecord record=null;
      // control flag for run loop
      // set true to exit loop
      public boolean done=false ;
      //private ClientProcessor processor;
      // our BT server connection
      public StreamConnectionNotifier notifier;
      private String appName ="SPPserver";
      //static Vector PhoneNumber=new Vector(1);
           //static int count;

           public bluetooth_server()
                {

                }
      public void run_server()
      {
           try
      {
      //
      // initialize the JABWT stack
      localdevice = LocalDevice.getLocalDevice(); // obtain reference to singleton
      localdevice.setDiscoverable(DiscoveryAgent.GIAC); // set Discover mode to GIAC
      //addr=localdevice.getBluetoothAddress();

      // start a thread to serve the server connection.
      // for simplicity of this demo, we only start one server thread
      // see run() for the task of this thread
      Thread t= new Thread(this);
      t.start();


      } catch ( BluetoothStateException e )
      {
      e.printStackTrace();
      }
      }//run_server



           
      public void run()

      StreamConnection c = null;

      try
      {
      String url = "btspp://localhost:" + uuid.toString() +";name="+ appName;
      System.out.println("server url: " + url );
      notifier = (StreamConnectionNotifier)Connector.open( url );
      // Retrieve the service record template
      record = localdevice.getRecord( notifier );
      record.setAttributeValue( ATTR_ID, new DataElement( DataElement.DATSEQ, 0xFF ) );
      //We choose Telephony Service
      record.setDeviceServiceClasses( SERVICE_TELEPHONY );
      //rec.setAttributeValue( 0x0008, new DataElement( DataElement.U_INT_1, 0xFF ) );



      } catch (Exception e)
      {
      //e.printStackTrace();
      System.out.println(e.getClass().getName()+" "+e.getMessage());
      }
      //processor = new ClientProcessor();

      while( !done)
      {
           
           DataInputStream in = null;
      DataOutputStream out=null;
      try {
      //////////////////////////////////////////////
      System.out.println(record);
      System.out.println("local service waiting for client connection...");

      // start accepting client connection.
      c = notifier.acceptAndOpen();
      System.out.println("accepted a client connection. reading its ID...");
      // retrieve the remote device object
      RemoteDevice rdev = RemoteDevice.getRemoteDevice( c );

      // retrieve the remote device object
      // RemoteDevice rdev = RemoteDevice.getRemoteDevice( c );
      //byte [] buffer=new byte[100];
      String msg="Hiiiiiiiiiiii Client";
      in = c.openDataInputStream();
      s=in.readUTF();
      System.out.println(s);
      out=c.openDataOutputStream();
      Thread.sleep(3000);
      out.writeUTF(msg);
      out.flush();
      c.close();
      //System.out.println(s);
      }
      catch(IOException e)
      {
           continue;
      //System.out.println(e.toString());
      }
      catch(InterruptedException e)
      {
           System.out.println(e.toString());
      }
      //processor.addConnection(c);
      /*try{
           c.close();
      in.close();
      out.close();
      }
      catch(IOException e)
      {
           System.out.println(e.toString());
      }*/

      }//end while
      }//run

      /*private class ClientProcessor implements Runnable {
      private Thread processorThread;
      private Vector queue = new Vector();
      private boolean isOk = true;

      ClientProcessor() {
      processorThread = new Thread(this);
      processorThread.start();
      }

      public void run() {
      while (!done) {

      wait for new task to be processed
      synchronized (this) {
      if (queue.size() == 0) {
      try {
      wait();
      } catch (InterruptedException e) {
      System.err.println("Unexpected exception: " + e);
      destroy(false);
      return;
      }
      }
      }

      send the image to specified connection
      StreamConnection conn=null;
      DataInputStream in = null;
      DataOutputStream out=null;
      synchronized (this) {

      may be awaked by "destroy" method.
      if (done) {
      return;
      }
      try
      {
      conn = (StreamConnection) queue.firstElement();
      queue.removeElementAt(0);
      processConnection(conn);
      String msg="Hiiiiiiiiiiii Client";
      in = conn.openDataInputStream();
      out=conn.openDataOutputStream();
      send data to the client
      out.writeUTF(msg);
      out.flush();
      read data from client
      s=in.readUTF();
      System.out.println(s);
      }
      catch(IOException e)
      {
           System.out.println(e);
      }
      try{                         
      in.close();
      out.close();
      conn.close();
      }
      catch(IOException e)
      {
           System.out.println(e.toString());
      }

      }
      }
      }
      void addConnection(StreamConnection conn) {
      synchronized (this) {
      queue.addElement(conn);
      notify();
      }
      }

      }*/


      }//end bluetooth_server class
      .........................................................................................................
      package bluetooth;
      import java.io.*;
      import java.util.*;
      import javax.microedition.io.*;
      import java.lang.*;
      import javax.bluetooth.*;
      import javax.microedition.lcdui.*;
      import javax.microedition.midlet.*;



      public class bluetooth_midlet extends MIDlet implements CommandListener
      {
      private static bluetooth_midlet instance;
      private static Display display;

      private Command connect=new Command("connect to client", Command.SCREEN, 1);
      private Command exit=new Command("Exit", Command.EXIT, 1);

      private Form frm=new Form("THIS IS TO TEST.....");
      //public Form frm1=new Form("ANSWER FROM SERVER.......");

      public static String Servicename;


      //public final static UUID uuid = new UUID("102030405060708090A0B0C0D0E0F010", false);
      // public ServiceRecord sr=null;


      bluetooth_server bserver = null;



      public bluetooth_midlet()
      {
      instance = this;
      bserver = new bluetooth_server();
      }

      /* Implements MIDlet lifecycle*/

      public void startApp()
      {
      display = Display.getDisplay(this);
      //phone.setString("");
      //txt1.setString("");

      //frm.append(bserver.s);
      frm.addCommand(connect);
      frm.addCommand(exit);
      frm.setCommandListener(this);
      display.setCurrent(frm);

      }


      public void pauseApp()
      {

      }


      public void destroyApp(boolean unconditional)
      {

      }

      public void commandAction(Command c, Displayable d)
      {


      if ( c==connect)
      {

      bserver.run_server();
      /*frm.append(bserver.s);
      display.setCurrent( frm );*/

      }

      if ( c==exit)
      {

      instance.destroyApp(true);
      instance.notifyDestroyed();
      instance = null;

      }

      }//commandAction
      }//end of bluetooth_midlet


      please mention the error of my coding....................please help me out........................it's very urgent
        • 1. Re: can't access services from server using JSR 82
          843851
          Ok, I havn't read all your code because it's quite a lot and I might have the answer for you already.

          Maybe the problem is that your Nokia is still connected to your computer.

          I had the same problem on my Nokia 6021. I installed my app through the Nokia PC Suite. And it showed all the devices, but it couldn't find any services on any of the devices. Which was strange because most devices have some standard services running. The problem was that after installing the app, the Nokia was still connected/paired with the PC. After deleting the pairing, services magically appeared.

          I hope this solves your problem (more than six months after your post ;) ).
          • 2. Re: can't access services from server using JSR 82
            843851
            Hello, thank you Matthijs, your advice worked in my case. I�m conecting my nokia 5200 and my PC with BlueCove. I disconnect an aplication called Sensor in this cell phone, whe i did that, the service (on the phone) that i had created, was discvered by my PC.