通过蓝牙发送消息:PC作为服务端

server端代码:

      工程需要引入bluecove-2.1.0.jar包文件

public class Server {
	private LocalDevice localDevice = null;
	private StreamConnectionNotifier notifier;
    
	public void start() throws Exception {
		localDevice = LocalDevice.getLocalDevice();
        localDevice.setDiscoverable(DiscoveryAgent.GIAC);
        
        String url="btspp://localhost:04c6093b00001000800000805f9b34fb";
        notifier = (StreamConnectionNotifier)Connector.open(url);
        
        while(true){
        	try{
                StreamConnection connection = notifier.acceptAndOpen();

            	Thread thread = new Thread(new ConnectionThread(connection));
            	thread.setDaemon(true);
                thread.start();
        	}catch(Exception ex){
        		ex.printStackTrace();
        	}
        }
	}
	
	public void stop(){ 
		if(notifier != null){
			try {
				notifier.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
        Server server = null;
        try {
        	server = new Server();
			server.start();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(server != null){
				server.stop();
			}
		}
	}
	
}

ConnectionThread类代码:

public class ConnectionThread implements Runnable {
	private StreamConnection connection;
	private InputStream in;
	private OutputStream out;
	
	public ConnectionThread(StreamConnection connection){
        this.connection = connection;
	}
	
	public void run() {
		 try{
             in = connection.openInputStream();
             out = connection.openOutputStream();
             
             byte[] buffer = new byte[128];
             int len = -1;

             while(true){                                
                 if((len=in.read(buffer)) != -1){                                        
                	 String cmd = new String(buffer, 0, len, Charset.forName("UTF-8"));
                     System.out.println(cmd);
                     
                     out.write("This message from server".getBytes());
                     out.flush();
                 }
             }
             
	     }catch(Exception ex){
	     	ex.printStackTrace();
	     }
	}

}

Android client端关键代码:

String address = "10:2A:7D:BA:81:4A";  //蓝牙地址
UUID uuid = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb"); 
				
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
socket.getOutputStream().write("this message from client".getBytes());

相关推荐