通过蓝牙发送消息:PC作为客户端
Android server端代码:
public class BluetoothServerThread extends Thread{ private BluetoothAdapter adapter = null; private UUID uuid = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb"); private BluetoothServerSocket serverSocket; @Override public void run() { try{ adapter = BluetoothAdapter.getDefaultAdapter(); //没有蓝牙设备 if(adapter == null){ throw new RuntimeException("Bluetooth not support!"); } //打开蓝牙 if(!adapter.isEnabled()){ adapter.enable(); } serverSocket = adapter.listenUsingRfcommWithServiceRecord("Name", uuid); while(true){ BluetoothSocket socket = serverSocket.accept(); executorService.execute(new SocketThread(socket)); } }catch(Exception ex){ logger.error("Run BluetoothServerThread Error", ex); stopServer(); } } public void stopServer(){ if(serverSocket != null){ try { serverSocket.close(); serverSocket = null; } catch (IOException e) { e.printStackTrace(); } } } }
SocketThread代码:
class SocketThread implements Runnable{ private BluetoothSocket socket; public SocketThread(BluetoothSocket socket){ this.socket = socket; } @Override public void run() { BufferedReader reader = null; PrintWriter writer = null; try{ reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); while(true){ String msg = reader.readLine(); logger.info(msg); writer.write("This message from server\r\n"); writer.flush(); } }catch(Exception ex){ logger.error("SocketThread Error", ex); if(socket != null){ try { socket.close(); socket = null; } catch (IOException ex2) { logger.error("Close Socket Error", ex2); } } } } }
PC 客户端代码:
UUID uuid = new UUID("04c6093b00001000800000805f9b34fb", false); DiscoveryAgent agent = LocalDevice.getLocalDevice().getDiscoveryAgent(); String connectionURL = agent.selectService(uuid, ServiceRecord.AUTHENTICATE_ENCRYPT, false); StreamConnection connection = null; PrintWriter writer = null; BufferedReader reader = null; try{ connection = (StreamConnection)Connector.open(connectionURL); reader = new BufferedReader(new InputStreamReader(connection.openInputStream())); writer = new PrintWriter(new OutputStreamWriter(connection.openOutputStream())); writer.write("This message from client\r\n"); writer.flush(); String data = reader.readLine(); System.out.println(data); }catch(Exception ex){ ex.printStackTrace(); }
相关推荐
80296330 2020-09-15
SeetyST 2020-08-13
张俊杰 2020-08-02
浅梦墨汐 2020-07-28
北落不吉 2020-06-27
棋牌游戏开发 2020-06-11
greenpepper 2020-06-11
greenpepper 2020-06-13
seek 2020-06-10
dotstar 2020-06-02
hushijiao 2020-05-17
浅梦墨汐 2020-05-12
chinaycheng 2020-05-06
sixforone 2020-05-06
海豚的成长日记 2020-05-04
greenpepper 2020-04-29
greenpepper 2020-04-22
海豚的成长日记 2020-01-12