通过蓝牙发送消息: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());
相关推荐
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