使用匹配的UUID将BluetoothServerSocket连接到BluetoothSocket

时间:2018-11-15 13:42:12

标签: java android bluetooth

我无法使用Android的蓝牙API连接到客户端套接字。我已经阅读了this post和其中提到的所有相关文章。我为客户端和服务器使用相同的UUID。服务器bluetoothSocket.connect()每次都超时,并引发异常 java.io.IOException: read failed, socket might closed or timeout, read ret: -1。我不确定在这种情况下我做错了。我一直在阅读Android蓝牙API文档和Chat应用程序代码示例,而我试图做的事情非常相似。我尝试取消配对并再次配对,但无济于事。

这是客户端代码,作为OnePlus A3003(Android 7.1.1)上的应用程序的一部分运行:

public class BluetoothTrafficLightConnectThread extends Thread {
    private BluetoothDevice bluetoothDevice;
    private BluetoothSocket bluetoothSocket;

    public BluetoothTrafficLightConnectThread(BluetoothDevice btDevice){
        BluetoothSocket tmp = null;
        bluetoothDevice = btDevice;
        boolean temp = btDevice.fetchUuidsWithSdp();
        UUID uuid = null;

        if(temp){
            uuid = btDevice.getUuids()[0].getUuid();
        }

        Log.i(tag, "SmartRide using UUID " + uuid);

        try{
            //MY_UUID is the app's UUID string, also used by the server code
            tmp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
        }
        catch(IOException e){
            Log.i(tag, "Get socket failed in BluetoothTrafficLightConnectThread");
        }

        bluetoothSocket = tmp;
    }

    public void run(){

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            bluetoothSocket.connect();
            Log.i(tag, "TrafficLightConnect succeeded.");
        }
        catch (IOException connectException) {
            Log.i(tag, "TrafficLightConnect failed.\n" + connectException.toString());

            try {
                bluetoothSocket.close();
            }
            catch (IOException closeException) {
                Log.i(tag, "Failed to close socket after connection unsuccessful." + closeException);
            }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        mHandler.obtainMessage(SUCCESS_CONNECT_TRAFFIC_LIGHT, bluetoothSocket).sendToTarget();
    }

    public void cancel(){
        try {
            bluetoothSocket.close();
        }
        catch (IOException e) {}
    }
}

运行在Samsung J5,Android版本8.1.0上的服务器代码:

private class AcceptThread extends Thread {
    // The local server socket - listens for incoming requests
    private final BluetoothServerSocket mmServerSocket;
    private String mSocketType;

    public AcceptThread(boolean secure){
        BluetoothServerSocket tmp = null;
        mSocketType = secure ? "Secure" : "Insecure";

        Log.d(TAG, "AcceptThread constructor");

        // Create a new listening server socket
        try{
            if(secure) {
                tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID);

                Log.d(TAG, "Have a secure rfcomm socket. " + tmp.toString());
                Log.d(TAG, "TrafficLight using UUID " + MY_UUID.toString());
            }
            else {
                tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME_INSECURE, MY_UUID);
                Log.d(TAG, "Have an insecure rfcomm socket." + tmp.toString());
            }

        } catch (IOException e) {
            Log.e(TAG, "Socket type: " + mSocketType + "listen() failed", e);
        }

        mmServerSocket = tmp;
        mState = STATE_LISTEN;

        updateUserInterfaceTitle();
    }

    @Override
    public void run(){
        Log.d(TAG, "Begin acceptThread");
        setName("AcceptThread" + mSocketType);

        BluetoothSocket socket = null;

        while(mState != STATE_CONNECTED){
            try{
                // This is a blocking call and will only return on a
                // successful connection or an exception
                Log.d(TAG, "Trying to connect to the remote device.");
                socket = mmServerSocket.accept();
                mmServerSocket.close();
                Log.d(TAG, "Accepted the incoming connection request.");
            } catch(IOException e){
                Log.e(TAG, "Socket Type: " + mSocketType + ", .accept() failed", e);
                break;
            }

            // Connection was accepted
            if(socket != null){
                synchronized(BluetoothTLService.this){
                    switch(mState){
                        case STATE_LISTEN:
                            Log.d(TAG, "Connection established.");
                            // Can terminate the AcceptThread as we are now connected
                            // Should notify others that we are ready to send data now
                            mIsConnected = true;
                            setUpConnection(socket, socket.getRemoteDevice(), mSocketType);
                            break;
                        case STATE_NONE:
                        case STATE_CONNECTED:
                            // Either not ready or already connected. Terminate new socket
                            try{
                                socket.close();
                                Log.d(TAG, "Closing socket.");
                            } catch(IOException e){
                                Log.e(TAG, "Could not close unwanted socket", e);
                            }
                            break;
                    }
                }
            }
        }

        Log.d(TAG, "END mAcceptThread, socket Type: " + mSocketType);
    }

    public void cancel(){
        Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);
        try {
            mmServerSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e);
        }
    }
}

0 个答案:

没有答案