我试图将文本从客户端android发送到PC上的服务器java
这是android端代码
protected static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private String BluetoothMacAddress = "A8:A7:95:65:26:BA";
protected void onCreate() {
initBluetoothDevice();
CheckBluetoothState();
device = mBluetoothAdapter.getRemoteDevice(getBluetoothMacAddress());
new Send("Hello from Client").execute();
mBluetoothAdapter.cancelDiscovery();
}
class Send extends AsyncTask<Void, Void, Void> {
BluetoothSocket btSocket;
//private Socket client;
private String TextMessage;
//private PrintWriter toServer;
protected OutputStream outStream = null;
public Send(String string) {
TextMessage = string;
}
@Override
protected Void doInBackground(Void... params) {
try {
Log.d(TAG, "doInBackground: "+TextMessage);
//client = new Socket(IpAdress, Port); // connect to the server Ip given by my mobile hotspot
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
outStream = btSocket.getOutputStream();
byte[] msgBuffer = TextMessage.getBytes();
outStream.write(msgBuffer);
outStream.flush();
btSocket.close(); // closing the connection
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
这是java代码
public class SimpleSPPServer {
StreamConnection connection;
StreamConnectionNotifier streamConnNotifier;
InputStream inStream;
BufferedReader bReader;
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("0001101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
//open server url
streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
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));
while(true){
try{
//streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
connection = streamConnNotifier.acceptAndOpen();
inStream = connection.openInputStream();
bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead = bReader.readLine();
System.out.println(lineRead);
inStream.close();
}catch(Exception e){
e.printStackTrace();
// break;
}
}
}
}
代码有效,但问题是收到的消息有时为空,有人能告诉我问题在哪里以及如何修复
答案 0 :(得分:0)
查看BufferedReader#readLine()
的文档,它将以下内容指定为返回值:
包含行内容的字符串,不包括任何行终止字符;如果已到达流的末尾,则为null
因此,当它返回null
时,表示基础数据流没有任何进一步的数据。通过蓝牙等两台计算机之间的任何通信,可能只是通信失败的情况,应该经常发生。