java蓝牙服务器将消息发送回客户端
我正在构建与android设备通信的简单java服务器(作为客户端)。目前我可以通过蓝牙从手机(客户端)向pc(服务器)发送信息。问题是我无法从服务器将消息发送回客户端。我正在使用bluecave图书馆。这是我的密码java蓝牙服务器将消息发送回客户端,java,bluetooth,server,outputstream,printwriter,Java,Bluetooth,Server,Outputstream,Printwriter,我正在构建与android设备通信的简单java服务器(作为客户端)。目前我可以通过蓝牙从手机(客户端)向pc(服务器)发送信息。问题是我无法从服务器将消息发送回客户端。我正在使用bluecave图书馆。这是我的密码 public class MainTest { UUID uuid = new UUID("8848",true); public static void main(String[] args) { LocalDevice local = null;
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());
}
}
以下答案解决了从服务器向android客户端发送文本消息的问题:
也许你可以在你的情况下使用它。抱歉,这可能是重复的,但没有帮助