如何在Java蓝牙服务器(PC)上连接多个客户端(android)

时间:2018-08-07 06:15:14

标签: java android bluetooth

我在一个需要多个客户端(Android)连接到服务器(PC)蓝牙的项目中。客户端需要向服务器发送多个字符串。我正在使用RFCOMM在客户端和服务器之间建立连接。我设法将字符串从客户端发送到服务器。我去过Google,发现关于我的问题的参考很少,我读到可以在服务器中使用不同的UUID,但仍然不知道该怎么做。


这是我的服务器程序:

public class ServerText {

 //start server
void startServer() throws IOException{
       //Create a UUID for SPP
    UUID uuid = new UUID("1101", true);
    //Create the servicve url
    String connectionString = "btspp://localhost:" + uuid +";name=Server Bluetooth 2";

    //open server url
    StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );

    //Wait for client connection
    System.out.println("\nServer Started. Waiting for clients to connect...");
    StreamConnection connection=streamConnNotifier.acceptAndOpen();

    RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
    System.out.println("Remote device address: "+dev.getBluetoothAddress());
    System.out.println("Remote device name: "+dev.getFriendlyName(true));


    InputStream inStream=connection.openInputStream();
    BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
    String lineRead=bReader.readLine();


    System.out.println(lineRead);


     streamConnNotifier.close();
     inStream.close();
     bReader.close(); 

}


public static void main(String[] args) throws IOException, SQLException{

    //display local device address and name
    LocalDevice localDevice = LocalDevice.getLocalDevice();
    System.out.println("Address: "+localDevice.getBluetoothAddress());
    System.out.println("Name: "+localDevice.getFriendlyName());

    ServerText serverbluetooth2=new ServerText();
    serverbluetooth2.startServer();   
}
}

这是我的客户程序:

 public class Bluetooth extends AppCompatActivity {
//TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;

// Well known SPP UUID
private static final UUID MY_UUID =
        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

//MAC address DC85DEF66492
private static String address = "DC:85:DE:F6:64:92";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);

    // out = (TextView) findViewById(R.id.out);

    // out.append("\n...In onCreate()...");

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    CheckBTState();
}
@Override
public void onStart() {
    super.onStart();
    //out.append("\n...In onStart()...");
}

@Override
public void onResume() {
    super.onResume();

    //out.append("\n...In onResume...\n...Attempting client connect...");

    // Set up a pointer to the remote node using it's address.
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    try {
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
        AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }

    // Discovery is resource intensive.  Make sure it isn't going on
    // when you attempt to connect and pass your message.
    btAdapter.cancelDiscovery();

    // Establish the connection.  This will block until it connects.
    try {
        btSocket.connect();
        //  out.append("\n...Connection established and data link opened...");
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {
            AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
        }
    }

    // Create a data stream so we can talk to server.
    //out.append("\n...Sending message to server...");

    try {

        outStream = btSocket.getOutputStream();
    } catch (IOException e) {
        AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
    }

    Intent intent = getIntent();
    String message = intent.getExtras().getString("pindah");
    byte[] msgBuffer = message.getBytes();

    if(btSocket.isConnected()) {
        try {
            outStream.write(msgBuffer);

            if (outStream != null) {
                try {
                    outStream.flush();
                } catch (IOException e) {
                    AlertBox("Fatal Error", "In onResume() and failed to flush output stream: " + e.getMessage() + ".");
                }
            }

            try     {
                btSocket.close();
            } catch (IOException e2) {
                AlertBox("Fatal Error", "In onResume() and failed to close socket." + e2.getMessage() + ".");
            }

        } catch (IOException e) {
            String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
            if (address.equals("00:00:00:00:00:00"))
                msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
            msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

            AlertBox("Fatal Error", msg);

        }
    }

}

@Override
public void onPause() {
    super.onPause();

    //out.append("\n...In onPause()...");

    //if (outStream != null) {
    //  try {
    //    outStream.flush();
    //} catch (IOException e) {
    //  AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
    //}
    //}

    //try     {
    //  btSocket.close();
    //} catch (IOException e2) {
    // AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    //}
}

@Override
public void onStop() {
    super.onStop();
    //out.append("\n...In onStop()...");
}

@Override
public void onDestroy() {
    super.onDestroy();
    //out.append("\n...In onDestroy()...");
}

private void CheckBTState() {
    // Check for Bluetooth support and then check to make sure it is turned on

    // Emulator doesn't support Bluetooth and will return null
    if(btAdapter==null) {
        AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
    } else {
        if (btAdapter.isEnabled()) {
            //out.append("\n...Bluetooth is enabled...");
        } else {
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }
}

public void AlertBox( String title, String message ){
    new AlertDialog.Builder(this)
            .setTitle( title )
            .setMessage( message + " Press OK to exit." )
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    finish();
                }
            }).show();
}

}

0 个答案:

没有答案