Android: connection between server and client

I am trying to connect to server and client Bluetooth. If so, sometimes it connects and works correctly, and sometimes it shows an error due to the fact that it is not connected to Socket.

I can not find a problem with this. The following code I used: -

private Runnable reader = new Runnable()
    {

        @Override
        public void run()
        {
            try 
            {
                android.util.Log.e("TrackingFlow Client", " Found: " + remoteDevice.getName());
                UUID uuid = UUID.fromString("4e5d48e0-75df-11e3-981f-0800200c9a66");
                socket = remoteDevice.createRfcommSocketToServiceRecord(uuid);
                socket.connect();

                android.util.Log.e("TrackingFlow Client", "Connected...");
                os = new OutputStreamWriter(socket.getOutputStream());
                is = socket.getInputStream();

                //new Thread(writter).start();
                android.util.Log.e("TrackingFlow Client", "CONTINUE_READ_WRITE" + CONTINUE_READ_WRITE);
                int bufferSize = 1024;
                int bytesRead = -1;
                byte[] buffer = new byte[bufferSize];
                //Keep reading the messages while connection is open...
                while(CONTINUE_READ_WRITE)
                {
                    android.util.Log.e("TrackingFlow Client", "Reading Started");
                    final StringBuilder sb = new StringBuilder();
                    bytesRead = is.read(buffer);
                    if (bytesRead != -1)
                    {
                        String result = "";
                        while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0))
                        {
                            result = result + new String(buffer, 0, bytesRead - 1);
                            bytesRead = is.read(buffer);
                        }
                            result = result + new String(buffer, 0, bytesRead - 1);
                            sb.append(result);
                    }

                    android.util.Log.e("TrackingFlow Client", "Read: " + sb.toString());

                    //Show message on UIThread
                    runOnUiThread(new Runnable()
                    {   
                        @Override
                        public void run() 
                        {
                            Toast.makeText(MainActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            } catch (IOException e) {e.printStackTrace();}
        }
    };
+4
source share

Source: https://habr.com/ru/post/1543340/


All Articles