私はアンドロイドデバイスと(クライアントとして)通信する単純なJavaサーバーを構築しています。現在、私の電話(クライアント)からブルートゥース経由で自分のPC(サーバー)にメッセージを送信できます。問題は、サーバーからクライアントにメッセージを送信できないことです。私はbluecaveライブラリを使用しています。以下の答えは、サーバーからのアンドロイドクライアントにテキストメッセージを送信するために問題を解決するためここに私のコードはjava bluetoothサーバーからクライアントにメッセージを返信する
public class MainTest {
UUID uuid = new UUID("8848",true);
public static void main(String[] args) {
LocalDevice local = null;
try {
local = LocalDevice.getLocalDevice();
} catch (BluetoothStateException e) {
e.printStackTrace();
}
System.out.println("Serverted:\n" +local.getBluetoothAddress() +"\n"+local.getFriendlyName());
MainTest ff = new MainTest();
while (true) {
ff.startserver();
}
}
public void startserver() {
try {
String url = "btspp://localhost:" + uuid + ";name=File Server";
StreamConnectionNotifier service = (StreamConnectionNotifier) Connector.open(url);
StreamConnection con = service.acceptAndOpen();
OutputStream dos = con.openOutputStream();
InputStream dis = con.openInputStream();
while (true) {
byte buffer[] = new byte[1024];
int bytes_read = dis.read(buffer);
String received = new String(buffer, 0, bytes_read);
System.out.println("Message:"+ received);
if("a".equals(received)) {
dos.write("sdfsd".getBytes());
dos.flush();
}
}
// con.close();
} catch (IOException e) {
System.err.print(e.toString());
}
}
だ私はまたPrintWriter
更新されたコードを使用しようとしましたが、それでも応答がない...
public static void startserver() {
try {
String url = "btspp://localhost:" + uuid + ";name=TTT";
StreamConnectionNotifier service = (StreamConnectionNotifier) Connector.open(url);
StreamConnection con = service.acceptAndOpen();
DataOutputStream dos = con.openDataOutputStream();
InputStream dis = con.openInputStream();
PrintWriter pWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(dos)), true);
while (true) {
byte buffer[] = new byte[10];
int bytes_read = dis.read(buffer);
String received = new String(buffer, 0, bytes_read);
System.out.println("Message:"+ received);
pWriter.write("testString");
pWriter.flush();
}
// pWriter.close();
// con.close();
// con.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
[JavaサーバーからAndroidクライアントにBluetooth経由でテキストを送信](http://stackoverflow.com/questions/10929767/send-text-through-bluetooth-from-java-server-to-android-client)の可能な複製) –