Search code examples
androidc++node.jssocketsbluetooth

serversocket to bluetooth serversocket


For the past couple of days, I have been working on establishing a client-server socket over Bluetooth with an android server and a windows PC socket so I can send information over from the computer that can be used on an app for Oculus Gear VR (app would be on the android). I am having a big issue with the Bluetooth server socket on the android side. It doesn't help that my experience with android studio is encompassed within like 4 days. I figured out how to create a regular server socket on an android app that waits for a connection from the client

public class MyServer {
    BluetoothDevice device;
    Thread  m_objThread;

    ServerSocket m_server;
    String m_strMessage;
    DataDisplay m_dataDisplay;
    Object m_connected;
    public MyServer()
    {

    }
    public void setEventListener(DataDisplay dataDisplay)
    {
        m_dataDisplay = dataDisplay;
    }
    public void startListening()
    {
       
        m_objThread = new Thread(new Runnable() {
            public void run() {
                try {
                    m_server = new ServerSocket(2001);
                    Socket connectedSocket = m_server.accept();
                    Message clientmessage = Message.obtain();
                    ObjectInputStream ois = new ObjectInputStream(connectedSocket.getInputStream());
                    String strMessage = (String) ois.readObject();
                    clientmessage.obj = strMessage;
                    mHandler.sendMessage(clientmessage);
                    ObjectOutputStream oos = new ObjectOutputStream(connectedSocket.getOutputStream());
                    oos.writeObject("Hi..");
                    ois.close();
                    oos.close();
                    m_server.close();
                } catch (Exception e) {
                    Message msg3 = Message.obtain();
                    msg3.obj = e.getMessage();
                    mHandler.sendMessage(msg3);
                }

            }
        });
        m_objThread.start();
    }
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message status)
        {
            m_dataDisplay.Display(status.obj.toString());
        }
    };

But I am not completely sure how to change this to a Bluetooth server socket in order to create a Bluetooth socket. Any help is appreciated, I am relatively new to coding and have only used c++ on visual studio so I am having a lot of trouble with android studio. Thanks!


Solution

  • You should create one thread for accepting a connection and another- for sending and receiving the data. When device is connected, you stop 'connect thread' and start 'transfer' thread. There is a gread example from google- https://github.com/googlesamples/android-BluetoothChat