×

Discussion Board

Results 1 to 4 of 4
  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    3

    Bluetooth connection working in emulator, but not working on Nokia E52

    Hi!

    I have a little problem with my J2ME application, I`m writing a game that can be played over the network, in case of 2 mobile phones using bluetooth communication. I was very happy when I got to the end of it and tried it out with Sun Java(TM) Wireless Toolkit 2.5.2 for CLDC emulator and everything seemed to work fine, but then installed it on 2 phones and nothing happened....
    The client/server class looks like this, I have to admit I found this example on the net:

    Code:
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.bluetooth.BluetoothStateException;
    import javax.bluetooth.DeviceClass;
    import javax.bluetooth.DiscoveryAgent;
    import javax.bluetooth.DiscoveryListener;
    import javax.bluetooth.LocalDevice;
    import javax.bluetooth.RemoteDevice;
    import javax.bluetooth.ServiceRecord;
    import javax.bluetooth.UUID;
    import javax.microedition.io.Connector;
    import javax.microedition.io.StreamConnection;
    import javax.microedition.io.StreamConnectionNotifier;
    
    public class ClientServer  implements DiscoveryListener{
    
        /** Creates a new instance of ClientServer */
       UUID RFCOMM_UUID = new UUID(0x0003);
       private String m_ServerUrl = "btspp://localhost:" + RFCOMM_UUID + ";name=rfcommtest;authorize=true";
       private StreamConnection m_StrmConn = null;
       private LocalDevice m_LclDevice = null;
       private InputStream m_Input=null;
       private OutputStream m_Output=null;
       private StreamConnectionNotifier  m_StrmNotf=null;
       public boolean m_bIsServer=false,m_bServerFound=false,m_bInitServer=false,m_bInitClient=false;
       private static String m_strUrl;
       private final String SEVER_RESPONSE= "RUN_THE_GAME",CLIENT_RESPONSE="CLIENT_IS_READY";
       private DiscoveryAgent m_DscrAgent=null;
    
        public ClientServer(boolean isServer)
        {
            m_bIsServer = isServer;
    
            if(m_bIsServer)
            {
                InitServer();
            }
            else
            {
                InitClient();
            }
    
    
    
        }
    
        private void InitServer()
        {
    
            m_strUrl= "btspp://localhost:" + RFCOMM_UUID + ";name=rfcommtest;authorize=true";
    
         // m_StrmConn = BTFACADE.waitForClient(SERVICE_NBR);
    
            try
            {
                  m_LclDevice = LocalDevice.getLocalDevice();
    
                  m_LclDevice.setDiscoverable(DiscoveryAgent.GIAC);
    
                  m_StrmNotf = (StreamConnectionNotifier)Connector.open(m_strUrl);
    
                  m_StrmConn = m_StrmNotf.acceptAndOpen();
    
                  m_bInitServer = true;
    
                  m_Output = m_StrmConn.openOutputStream();
                  m_Input = m_StrmConn.openInputStream();
            }
            catch (BluetoothStateException e)
            {
                System.err.println( "BluetoothStateException: " + e.getMessage() );
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
            catch(Exception e)
            {
                System.err.println( "Exception: " + e.getMessage() );
            }
    
        }
    
        private void InitClient()
        {
             SearchAvailDevices();
    
        }
    
        public void SearchAvailDevices()
        {
            try
            {
                //First get the local device and obtain the discovery agent.
                m_LclDevice = LocalDevice.getLocalDevice();
    
                m_DscrAgent=  m_LclDevice.getDiscoveryAgent();
    
                m_DscrAgent.startInquiry(DiscoveryAgent.GIAC,this);
            }
            catch (BluetoothStateException ex)
            {
                System.out.println("Problem in searching the blue tooth devices");
                ex.printStackTrace();
            }
    
        }
    
    
       public void SendMessages(String v_strData)
      {
          if((m_bInitClient) || (m_bInitServer) )
          {
                try
                {
                    m_Output.write(v_strData.length());
                    m_Output.write(v_strData.getBytes());
    
                }
                catch (IOException ex)
                {
                    ex.printStackTrace();
                }
    
          }
      }
    
    
       public String  RecieveMessages()
       {
           byte[] data = null;
    
           try
           {
    
              int length = m_Input.read();
              data= new byte[length];
              length = 0;
    
              while (length != data.length)
              {
                      int ch = m_Input.read(data, length, data.length - length);
    
                      if (ch == -1)
                      {
                        throw new IOException("Can't read data");
                      }
                      length += ch;
              }
    
    
           }
           catch (IOException e)
           {
                 System.err.println(e);
           }
    
    
           return new String(data);
       }
    
    
       /*********************************************************************************************
       * below are the pure virtual  methods of discoverlistern
       *
       *
       *******************************************************************************************/
    
    
      public void inquiryCompleted(int discType)
      {
            System.out.println("InquiryCompleted");
    
      }
    
      //called when service search gets complete
      public void serviceSearchCompleted(int transID, int respCode)
      {
          if(m_bServerFound)
          {
                try
                {   //lets the communication start by setting the url and send client reponse
                    m_StrmConn = (StreamConnection) Connector.open(m_strUrl);
    
                    m_Output = m_StrmConn.openOutputStream();
                    m_Input = m_StrmConn.openInputStream();
    
                    m_Output.write(CLIENT_RESPONSE.length());
                    m_Output.write(CLIENT_RESPONSE.getBytes());
    
                     System.out.println("serviceSearchCompleted");
                }
                catch (IOException ex)
                {
                    ex.printStackTrace();
                }
    
          }
      }
    
      void CloseAll()
      {
            try
            {
                if(m_Output!=null)
                    m_Output.close();
    
                if( m_Input!=null)
                     m_Input.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
    
      }
    
    
    
      //called when service found during service search
      public void servicesDiscovered(int transID, ServiceRecord[] records)
      {
    
        for (int i = 0; i < records.length; i++)
        {
            m_strUrl = records[i].getConnectionURL(ServiceRecord.AUTHENTICATE_ENCRYPT, false);
    
            System.out.println(m_strUrl);
            if(m_strUrl.startsWith("btspp")) //we have found our service protocol
            {
                m_bServerFound = true;
                m_bInitClient=true;
               break;
            }
    
        }
    
    
      }
    
      //Called when device is found during inquiry
      public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod)
      {
    
         try
         {
          // Get Device Info
          System.out.println("Device Discovered");
          System.out.println("Major Device Class: " + cod.getMajorDeviceClass() + " Minor Device Class: " + cod.getMinorDeviceClass());
          System.out.println("Bluetooth Address: " + btDevice.getBluetoothAddress());
          System.out.println("Bluetooth Friendly Name: " + btDevice.getFriendlyName(true));
    
          // Search for Services
          UUID uuidSet[] = new UUID[1];
          uuidSet[0] =  RFCOMM_UUID;
          int searchID = m_DscrAgent.searchServices(null,uuidSet,btDevice,this);
        }
        catch (Exception e)
        {
          System.out.println("Device Discovered Error: " + e);
        }
    
    
      }
    
    }
    in my midlet application I do the following:

    Code:
    switch (blueForm.getSelectedIndex()) {
                        case 0:
                            //SERVER
                            if(m_bRunThread==false)
                            {
                                Thread thread = new Thread(this); 
                                thread.start();
                                m_bRunThread=true;
                                m_bIsServer=true;
                                k=1;
                                gameCanvas = new MyCanvas(false, this, gameType, gameDiff,m_bRunThread,m_bIsServer);
                            }
                            break;
                        case 1:
                            //CLIENT
                            if(m_bRunThread==false)
                            {
                                Thread thread = new Thread(this);
                                thread.start();
                                m_bRunThread=true;
                                m_bIsServer=false;
                                k=1;
                                gameCanvas = new MyCanvas(false, this, gameType, gameDiff,m_bRunThread,m_bIsServer);
                            }
                            break;
                    }
    gameCanvas is the class of the game itself-in gameCanvas I call the function SendMessages(String msg) if something happens that needs to be sent to the opponent player.

    And still in the midlet I have this code part:

    Code:
    public void run()
        {
            while(m_bRunThread)
            {
                try
                {
                        if(m_BlueObj==null)
                        {
                            m_BlueObj=new ClientServer(m_bIsServer);
                        }
                        String str = m_BlueObj.RecieveMessages();
                        gameCanvas.receivedmsg(str);
    
                        Thread.sleep(1000);
                }
                catch(Exception ex)
                {
                    System.out.println(ex.getMessage());
                }
    
             }
        }
    Any ideas anybody?It would be quite urgent to resolve this problem.
    PLS!!!!
    Thanks
    Br,
    Jules

  2. #2
    Registered User
    Join Date
    May 2011
    Posts
    3

    Angry Re: Bluetooth connection working in emulator, but not working on Nokia E52

    Wow my post got 165 views but no reply, thank you guys!
    Hoping there is at least one good-hearted expert out there I made some progress with my application, but it`s still not working 100%.
    I modified my code this way:
    Server:
    Code:
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.util.Vector;
    
    import javax.bluetooth.DiscoveryAgent;
    import javax.bluetooth.LocalDevice;
    import javax.bluetooth.UUID;
    import javax.microedition.io.Connector;
    import javax.microedition.io.StreamConnection;
    import javax.microedition.io.StreamConnectionNotifier;
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.AlertType;
    
    public class Bluetoothserver implements Runnable{
    
    	private StreamConnectionNotifier con;
    	Vector conections, inputs, outputs;
    	Thread t;
    	private int numClients;
            private Touche parentMidlet;
    
    
    	public Bluetoothserver(Touche parent) {
    		this.numClients = 1;
    		conections = new Vector();
    		inputs = new Vector();
                    outputs = new Vector();
                    parentMidlet = parent;
    		t = new Thread(this);
    		t.start();
    	}
    
    	public void run() {
    		createConnections();
    	}
    
    	/*
    	 * For each client we open a new connection and a new DataInputStream.
    	 * After create the new connection, we put it in a vector called conections.
    	 * After create the new DataInputStream, we put it in a vector called inputs.
    	 *
    	 * These two vectors function like a map.
    	 */
    	private void createConnections() {
    		UUID uuid = new UUID(0x0003);
    		LocalDevice localDevice;
    		try {
    			localDevice = LocalDevice.getLocalDevice();
    			localDevice.setDiscoverable(DiscoveryAgent.GIAC);
    			con = (StreamConnectionNotifier) Connector
    					.open("btspp://localhost:" + uuid
    							+ ";name=test;authorize=false");
                            Alert al= new Alert(null,"anyad:"+con, null, AlertType.ERROR);
                            al.setTimeout(10000);
                            parentMidlet.getDisplay().setCurrent(al);
    
    				StreamConnection conn = con.acceptAndOpen();
    				DataInputStream in = conn.openDataInputStream();
                                    DataOutputStream out = conn.openDataOutputStream();
    
    				conections.addElement(conn);
    				inputs.addElement(in);
                                    outputs.addElement(out);
    
    		} catch (Exception e) {
    			System.out.println("lancei exceptions!");
    		}
    	}
    
    public void SendMessages(String v_strData)
      {
                try
                {
                    DataOutputStream output = (DataOutputStream) outputs.elementAt(0);
                    output.write(v_strData.length());
                    output.write(v_strData.getBytes());
    
                }
                catch (IOException ex)
                {
                    Alert al= new Alert(null,"sendmessage error", null, AlertType.ERROR);
                    al.setTimeout(10000);
                    parentMidlet.getDisplay().setCurrent(al);
                    ex.printStackTrace();
                }
      }
    
    
       public String  RecieveMessages()
       {
           byte[] data = null;
           String msg=null;
    
           try
           {
              DataInputStream input = (DataInputStream) inputs.elementAt(0);
              int length = input.read();
              data= new byte[length];
              length = 0;
    
              while (length != data.length)
              {
                      int ch = input.read(data, length, data.length - length);
    
                      if (ch == -1)
                      {
                        throw new IOException("Can't read data");
                      }
                      length += ch;
              }
    
    
           }
           catch (IOException e)
           {
               Alert al= new Alert(null,"receivemessage error", null, AlertType.ERROR);
                    al.setTimeout(10000);
                    parentMidlet.getDisplay().setCurrent(al);
                 System.err.println(e);
           }
           msg = new String(data);
           Alert al= new Alert(null,"received message"+msg, null, AlertType.ERROR);
           al.setTimeout(1000);
           parentMidlet.getDisplay().setCurrent(al);
           return msg;
       }
    }

  3. #3
    Registered User
    Join Date
    May 2011
    Posts
    3

    Angry Re: Bluetooth connection working in emulator, but not working on Nokia E52

    And here is the Client part

    Client:
    Code:
    package Touche;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.bluetooth.BluetoothStateException;
    import javax.bluetooth.DeviceClass;
    import javax.bluetooth.DiscoveryAgent;
    import javax.bluetooth.DiscoveryListener;
    import javax.bluetooth.LocalDevice;
    import javax.bluetooth.RemoteDevice;
    import javax.bluetooth.ServiceRecord;
    import javax.bluetooth.UUID;
    import javax.microedition.io.Connector;
    import javax.microedition.io.StreamConnection;
    import javax.microedition.io.StreamConnectionNotifier;
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.AlertType;
    
    /*
     * Bluetoothclient.java
     *
     * Created on December 4, 2006, 1:40 AM
     *
     * To change this template, choose Tools | Template Manager
     * and open the template in the editor.
     */
    
    /**
     *
     * @author Farhan Hameed Khan
     */
    public class Bluetoothclient  implements DiscoveryListener,Runnable{
    
        /** Creates a new instance of Bluetoothclient */
       UUID RFCOMM_UUID = new UUID(0x0003);
       private StreamConnection m_StrmConn = null;
       private LocalDevice m_LclDevice = null;
       private InputStream m_Input=null;
       private OutputStream m_Output=null;
       public boolean m_bIsServer=false,m_bServerFound=false,m_bInitServer=false,m_bInitClient=false;
       private static String m_strUrl;
       private final String CLIENT_RESPONSE="CLIENT_IS_READY";
       private DiscoveryAgent m_DscrAgent=null;
       private Touche parentMidlet;
       private RemoteDevice btDevice;
        private UUID uuid;
    
        public Bluetoothclient(Touche parent)
        {
            parentMidlet = parent;
            InitClient();
        }
    
        
        private void InitClient()
        {
             SearchAvailDevices();
        }
    
        public void SearchAvailDevices()
        {
            try
            {
                //First get the local device and obtain the discovery agent.
                m_LclDevice = LocalDevice.getLocalDevice();
    
                m_DscrAgent=  m_LclDevice.getDiscoveryAgent();
    
                m_DscrAgent.startInquiry(DiscoveryAgent.GIAC,this);
            }
            catch (BluetoothStateException ex)
            {
                Alert al= new Alert(null,"Problem in searching the blue tooth devices", null, AlertType.ERROR);
                al.setTimeout(10000);
                parentMidlet.getDisplay().setCurrent(al);
                System.out.println("Problem in searching the blue tooth devices");
                ex.printStackTrace();
            }
    
        }
    
    
       public void SendMessages(String v_strData)
      {
                try
                {
                    m_Output.write(v_strData.length());
                    m_Output.write(v_strData.getBytes());
    
                }
                catch (IOException ex)
                {
                    Alert al= new Alert(null,"sendmessage error", null, AlertType.ERROR);
                    al.setTimeout(10000);
                    parentMidlet.getDisplay().setCurrent(al);
                    ex.printStackTrace();
                }
      }
    
    
       public String  RecieveMessages()
       {
           byte[] data = null;
           String msg;
           try
           {
    
              int length = m_Input.read();
              data= new byte[length];
              length = 0;
    
              while (length != data.length)
              {
                      int ch = m_Input.read(data, length, data.length - length);
    
                      if (ch == -1)
                      {
                        throw new IOException("Can't read data");
                      }
                      length += ch;
              }
    
    
           }
           catch (IOException e)
           {
               Alert al= new Alert(null,"receivemessage error", null, AlertType.ERROR);
                    al.setTimeout(10000);
                    parentMidlet.getDisplay().setCurrent(al);
                 System.err.println(e);
           }
           msg = new String(data);
           Alert al= new Alert(null,"received message"+msg, null, AlertType.ERROR);
           al.setTimeout(1000);
           parentMidlet.getDisplay().setCurrent(al);
           return msg;
       }
    
    
       /*********************************************************************************************
       * below are the pure virtual  methods of discoverlistern
       *
       *
       *******************************************************************************************/
    
    
      public void inquiryCompleted(int discType)
      {
            System.out.println("InquiryCompleted");
    
      }
    
      //called when service search gets complete
      public void serviceSearchCompleted(int transID, int respCode)
      {
          if(m_bServerFound)
          {
                try
                {   //lets the communication start by setting the url and send client reponse
                    m_StrmConn = (StreamConnection) Connector.open(m_strUrl);
    
                    Alert al= new Alert(null,"StreamConnection"+m_StrmConn, null, AlertType.ERROR);
                    al.setTimeout(10000);
                    parentMidlet.getDisplay().setCurrent(al);
    
                    m_Output = m_StrmConn.openOutputStream();
                    m_Input = m_StrmConn.openInputStream();
                    
    
                    m_Output.write(CLIENT_RESPONSE.length());
                    m_Output.write(CLIENT_RESPONSE.getBytes());
    
                    //Alert al= new Alert(null,"serviceSearchCompleted"+ m_Output+m_Input, null, AlertType.ERROR);
                    //al.setTimeout(20000);
                    //parentMidlet.getDisplay().setCurrent(al);
                    System.out.println(m_strUrl);
                     System.out.println("serviceSearchCompleted");
                }
                catch (IOException ex)
                {
                    Alert al= new Alert(null,"service search completed", null, AlertType.ERROR);
                    al.setTimeout(10000);
                    parentMidlet.getDisplay().setCurrent(al);
                    ex.printStackTrace();
                }
    
          }
      }
    
      void CloseAll()
      {
            try
            {
                if(m_Output!=null)
                    m_Output.close();
    
                if( m_Input!=null)
                     m_Input.close();
            }
            catch (IOException ex)
            {
                Alert al= new Alert(null,"closeall error", null, AlertType.ERROR);
                    al.setTimeout(10000);
                    parentMidlet.getDisplay().setCurrent(al);
                ex.printStackTrace();
            }
    
      }
    
    
    
      //called when service found during service search
      public void servicesDiscovered(int transID, ServiceRecord[] records)
      {
    
        for (int i = 0; i < records.length; i++)
        {
            try {
                m_strUrl = records[i].getConnectionURL(ServiceRecord.AUTHENTICATE_ENCRYPT, false);
                Alert al= new Alert(null,"m_strUrl "+m_strUrl, null, AlertType.ERROR);
                al.setTimeout(20000);
                parentMidlet.getDisplay().setCurrent(al);
            }
            catch (Exception e) {
                Alert al= new Alert(null,"servicesDiscovered", null, AlertType.ERROR);
                al.setTimeout(10000);
                parentMidlet.getDisplay().setCurrent(al);
            }
    
            System.out.println(m_strUrl);
            if(m_strUrl.startsWith("btspp")) //we have found our service protocol
            {
                //Alert al= new Alert(null,"m_strUrl.startsWith btgoep", null, AlertType.ERROR);
                //al.setTimeout(20000);
               // parentMidlet.getDisplay().setCurrent(al);
                m_bServerFound = true;
                m_bInitClient=true;
               break;
            }
    
        }
    
    
      }
    
      //Called when device is found during inquiry
      public void deviceDiscovered(RemoteDevice btDevice2, DeviceClass cod)
      {
    
         Thread t = new Thread(this);
         t.start();
         btDevice = btDevice2;
    
      }
    
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
         try
         {
    
    
         if(m_DscrAgent != null){
    
            if (btDevice != null)
            {
    
          // Search for Services
          UUID uuidSet[] = new UUID[1];
          uuidSet[0] =  RFCOMM_UUID;
          int searchID = m_DscrAgent.searchServices(null,uuidSet,btDevice,this);
    
          //Alert al= new Alert(null,"After search_services", null, AlertType.ERROR);
            //        al.setTimeout(10000);
              //      parentMidlet.getDisplay().setCurrent(al);
             }
            else
            {
                     Alert al= new Alert(null,"btDevice null!!!", null, AlertType.ERROR);
                    al.setTimeout(10000);
                    parentMidlet.getDisplay().setCurrent(al);
            }
             }
         else
         {
             Alert al= new Alert(null,"m_DscrAgent null!!!", null, AlertType.ERROR);
                    al.setTimeout(10000);
                    parentMidlet.getDisplay().setCurrent(al);
         }
        }
        catch (Exception e)
        {
            Alert al= new Alert(null,"Device Discovered Error: " + e, null, AlertType.ERROR);
                    al.setTimeout(10000);
                    parentMidlet.getDisplay().setCurrent(al);
          System.out.println("Device Discovered Error: " + e);
        }
        }
    
    }
    Now when I run my code, the little bluetooth communication icon appears near the bluetooth icon. Now it seems that both the client and server connect and create streams, but don`t receive each others messages, it`s like they are talking in parallel...SOMEBODY anybody any ideeas??? PLEASE!!! pretty please!!

  4. #4
    Registered User
    Join Date
    Mar 2003
    Posts
    4,105

    Re: Bluetooth connection working in emulator, but not working on Nokia E52

    You use the wrong UUID. You have to create your own private (= long) one, instead of using 0x0003. A real phone has several services based on 0x0003 and your client uses one of those instead of contacting your server.

Similar Threads

  1. Replies: 3
    Last Post: 2011-02-27, 10:30
  2. Replies: 24
    Last Post: 2009-05-29, 07:12
  3. UDP connection to server working on emulator but not on device !
    By symbian2006 in forum Symbian Networking & Messaging (Closed)
    Replies: 7
    Last Post: 2008-10-21, 14:29
  4. http connection in J2me(working fine in emulator but not in real device)???
    By prasad767 in forum Mobile Java Networking & Messaging & Security
    Replies: 2
    Last Post: 2006-11-29, 06:14
  5. Replies: 2
    Last Post: 2006-03-11, 10:29

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×